【问题标题】:How to create a new variable on condition of others in R如何在R中其他人的条件下创建一个新变量
【发布时间】:2021-01-14 08:57:52
【问题描述】:

我有以下数据框:

ID   Measurement A      Measurement  B     Date of Measurements A and B   Date of Measurement C
1    23                 24                 12                             16
1    22                 23                 12                             15
1    24                 22                 12                             17
1    21                 20                 12                             11
1    27                 29                 12                             17

这是使用 1 个标识符 (ID) 的示例,实际上我有数千个。

我想创建一个封装的变量

"如果此 ID 的测量 A 或测量 B 大于 xxx,在测量 C 的日期之前,超过两次,则指定 它们在名为 new_var 的新列中为 1。

到目前为止,我删除了所有测量日期 A 和 B > 测量日期 C

measurements <- subset(measurements, dateofmeasurementsAandB < dateofmeasurementC)

然后在 ifelse 语句中的截断处添加

measurements$new_var<- ifelse(measurements$measurementA >= xxx | measurements$measurementB >= xxx, 1, 0)

但不能考虑“在多个场合”(从示例中可以看出,每个 ID 都有多个行/场合)

任何帮助都会很棒,尤其是如果它可以做得更简单!

【问题讨论】:

    标签: r if-statement variables conditional-statements


    【解决方案1】:

    如果我不明白你在问什么,我想我会使用 dplyr 的计数功能:

    #Starting from your dataframe
    library(tidyverse)
    df <- measurements %>%
             filter(dateofmeasurementsAandB < dateofmeasurementC,
                    measurements$measurementA >= xxx | measurements$measurementB >= xxx)
    

    这个数据框应该只有你想要的条件,所以现在我们计算它们并过滤结果:

    df <- df %>% count(ID) %>% filter(n >= 2)
    

    矢量 df$ID 现在应该只包含多次测量的 ID,然后您可以轻松地将其反馈到您的 measurements 数据框中,但是我偏爱这个:

    measurements$new_var <- 0
    measurements[measurements$ID %in% df$ID]$new_var <- 1
    

    【讨论】:

    • 您好,非常感谢!但是我如何包含条件'如果测量$measurementA >= xxx |测量$measurementB >= xxx 不止一次”?因为每个 ID 都有多个测量值,所以我需要找到具有测量值的行 $measurementA >= xxx |每个 ID 不止一次的测量 $measurementB >= xxx。抱歉不清楚!
    • 所以,我做的第一件事是过滤以确保您想要的所有事情都是真实的(即 A 和 B 都大于某个数字并且 AB 的日期在 C 之前)。然后 count 语句进入并在每次发生这种情况时按 ID 分组进行计数。如果该计数大于 1,则它一定发生了多次。
    猜你喜欢
    • 1970-01-01
    • 2022-07-15
    • 2020-05-26
    • 2021-12-09
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    相关资源
    最近更新 更多