如何从 R 获取输出并将每部分输出存储到单独的列中?

问题描述 投票:0回答:1

我正在使用 RStudio 中的“preventr”功能。它基本上是一个使用大约 10 个参数来预测患者心血管疾病风险的方程。我有一个包含超过 50,000 个观察值的数据框,每一行代表一个独特的患者及其独特的参数(风险建模所需的所有参数)。我想通过使用 Preventr 包(具体来说,函数:estimate_risk)来计算他们的心血管疾病风险。如何将输出(以小标题的形式)保存到原始数据框中每个参与者的新列中,其中包含估计风险所需的所有参数?请注意,estimate_risk函数输出是一个包含多个风险预测的小标题,我想将每个风险预测保存在单独的唯一列中。请参考下面的代码和输出。

df1: df1

install.packages("preventr")
library(preventr)
estimate_risk(
  age = df1$AGE,
  sex = df1$SEX,
  sbp = df1$SystolicBPAvg,
  bp_tx = df1$AnyAntihypertensive,
  total_c = df1$TCHOL,
  hdl_c = df1$HDL,
  statin = df1$AnticholesterolDrug,
  dm = df1$Diabetes,
  smoking = df1$CurrentSmoking,
  egfr = df1$eGFR,
  bmi = df1$BMI,
  hba1c = df1$A1c,
  uacr = df1$UACR,
)

#Example input#:
estimate_risk(
  age = 54,
  sex = "female",
  sbp = 151,
  bp_tx = TRUE,
  total_c = 197,
  hdl_c = 47,
  statin = FALSE,
  dm = FALSE,
  smoking = TRUE,
  egfr = 88,
  bmi = 32,
  hba1c = 6.2,
  uacr = 70,
)

#Example output#:
$risk_est_10yr
# A tibble: 1 × 8
  total_cvd ascvd heart_failure   chd stroke model over_years input_problems
      <dbl> <dbl>         <dbl> <dbl>  <dbl> <chr>      <int> <chr>         
1     0.138 0.076         0.067 0.036  0.044 full          10 NA            

$risk_est_30yr
# A tibble: 1 × 8
  total_cvd ascvd heart_failure   chd stroke model over_years input_problems
      <dbl> <dbl>         <dbl> <dbl>  <dbl> <chr>      <int> <chr>         
1     0.447 0.269         0.295 0.145  0.163 full          30 NA            


我希望能够保存 10 年估计和 30 年估计的总心血管疾病风险、ascvd 风险、心力衰竭风险、先心病风险、中风风险的输出。例如,列如下:total_cvd_10yr、ascvd_10yr、heart_failure_10yr、chd_10yr、strike_10yr、total_cvd_30yr、ascvd_30yr、heart_failure_30yr、chd_30yr 和Stroke_30yr。

我将非常感谢您的帮助。如果您需要更多信息,请告诉我。谢谢!!

r function output calculated-columns
1个回答
0
投票
library(tidyverse)
est1 |>
  list_rbind(names_to = "time") |>
  mutate(time = str_remove(time, "risk_est_")) |>
  pivot_wider(names_from = time, values_from = 2:9, names_vary = "slowest")
  

结果

  total_cvd_10yr ascvd_10yr heart_failure_10yr chd_10yr stroke_10yr model_10yr over_years_10yr input_problems_10yr total_cvd_30yr ascvd_30yr heart_failure_30yr chd_30yr stroke_30yr model_30yr over_years_30yr input_problems_30yr
           <dbl>      <dbl>              <dbl>    <dbl>       <dbl> <chr>                <int> <chr>                        <dbl>      <dbl>              <dbl>    <dbl>       <dbl> <chr>                <int> <chr>              
1          0.138      0.076              0.067    0.036       0.044 full                    10 NA                           0.447      0.269              0.295    0.145       0.163 full                    30 NA      

使用

est1 <- preventr::estimate_risk(
  age = 54,
  sex = "female",
  sbp = 151,
  bp_tx = TRUE,
  total_c = 197,
  hdl_c = 47,
  statin = FALSE,
  dm = FALSE,
  smoking = TRUE,
  egfr = 88,
  bmi = 32,
  hba1c = 6.2,
  uacr = 70,
) 
© www.soinside.com 2019 - 2024. All rights reserved.