【发布时间】:2023-07-13 11:34:01
【问题描述】:
我写了一个函数来谴责我的数据进行一些 cox 分析。
一些数据
data <- structure(list(Death1 = c("t", "f", "f", "f", "f", "f", "t",
"t", "f", "f", "f", "f", "f", "t", "f"), Death2 = c("t", "f",
"f", "t", "f", "f", "t", "t", "f", "f", "t", "t", "f", "t", "f"
), LastAge1 = c(5L, 78L, 62L, 71L, 74L, 114L, 5L, 2L, 77L, 91L,
71L, 74L, 92L, 29L, 73L), LastAge2 = c(6L, 74L, 59L, 31L, 71L,
127L, 8L, 8L, 69L, 91L, 11L, 14L, 102L, 22L, 66L), DES1 = c("e",
"e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
"e"), DES2 = c("e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
"e", "e", "e", "e", "e")), class = "data.frame", row.names = c(NA,
-15L))
这是我的功能
Censoring <- function(data, x){
usethis::ui_done("function that censure the last age and death")
data %>% mutate("Death{x}1" := case_when(Death1 == "f" & LastAge1 >=x ~ 0, # Right censoring
Death1 == "t" & LastAge1 < x ~ 1,
Death1 == "t" & LastAge1 >=x ~ 0,
Death1 == "f" & LastAge1 < x ~ NA_real_,
TRUE ~ NA_real_)) %>%
mutate("Death{x}2" := case_when(Death2 == "f" & LastAge2 >=x ~ 0,
Death2 == "t" & LastAge2 < x ~ 1,
Death2 == "t" & LastAge2 >=x ~ 0,
Death2 == "f" & LastAge2 < x ~ NA_real_,
TRUE ~ NA_real_)) %>%
mutate("Time{x}1" := case_when("Death{x}1" == 0 ~ x,
"Death{x}1" == 1 ~ as.numeric(LastAge1))) %>%
mutate("Time{x}2" := case_when("Death{x}2" == 0 ~ x,
"Death{x}2" == 1 ~ as.numeric(LastAge2))) %>%
mutate("Death{x}2" := case_when(DES2 != "e" ~ 1,
DES2 == "a" ~ NA_real_,
TRUE ~ "Death{x}2")) %>% # Case when we include egg survival
mutate("Time{x}2" := case_when(DES2 != "e" ~ 0,
DES2 == "a" ~ NA_real_,
TRUE ~ "Time{x}2")) # Case when egg survival is included
}
我遇到的问题是当我需要在 case_when("Death{x}1" == 0) 等条件下使用创建的变量(即 Death{x}1)时。我如何告诉 R 使用以前创建的变量。 (我尝试使用 paste0(Death, x, 1) 或 str_glue(Death{x}1) 但仍然无法正常工作)
谢谢
PS:如果有人对问题标题有更好的想法,请告诉我。
【问题讨论】:
-
您的
dput不完整。 -
ups 抱歉,现在已修复
标签: r function dplyr tidyverse rlang