R语言 当满足条件/疾病时,结合两个年龄变量[关闭]

qmelpv7a  于 2023-04-03  发布在  其他
关注(0)|答案(2)|浏览(98)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
4天前关闭。
Improve this question
当参与者在调查日期前5年或不到5年被诊断患有该疾病时,我想将该参与者标记为“具有感兴趣的结果”。
所以我想指定:疾病=是&诊断年龄=与调查时的年龄相比〈= 5岁。
我想一定是这样的,但我在网上找不到答案。

data <- mutate(variable_x = case_when(variable_a == 1 & (variable_b == - <=5 years than variable_c) ~ disease, variable_a == 0 ~ disease))

variable_x is the new variable 
variable_a is the old variable (simply disease 'yes or no')
variable_b is the age when diagnosed with disease
variable_c is age at time of the survey

我在网上找不到任何关于如何做到这一点的东西。有人能帮我吗?

aydmsdu9

aydmsdu91#

在发布查询时创建minimal reproducible example总是很好的。
不确定你的数据是什么样子的,但是假设你有一个这样的数据框:

# Dummy Data
df <- tibble::tibble(
  Pateint = c(LETTERS[1:5]),
  Disease = c('Y', 'N', 'N', 'Y', 'N'),
  Survey_Date = rep(Sys.Date(), 5)
)

# Adding Diagnosis Date
df <- df %>% dplyr::rowwise() %>% 
  dplyr::mutate(Diagnosis_Date = Survey_Date - round(rnorm(1, mean = 5*365, sd = 150)))

然后可以使用mutatecase_when添加所需的列

# Adding Outcome of Interest
df <- df %>% dplyr::mutate(Outcome_Of_Interest = dplyr::case_when(
  Disease == 'Y' & difftime(Diagnosis_Date, Survey_Date) <= 5*365 ~ 'Y',
  TRUE ~ 'N'
))
bqucvtff

bqucvtff2#

它非常简单,你甚至不需要使用mutate或任何复杂的东西。
假设您有一个名为df的data.frame,其中列名为diseaseage
然后,您可以使用以下命令创建新列:

df$ofinterest = df$disease == "yes" & df$age<=5

ofinterest将是一个新列,当满足条件时,值为TRUE,当不满足条件时,值为FALSE

相关问题