如果 Dataframe 中至少有两个变量具有相同的响应,则创建新列

20jt8wwn  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(100)

我尝试了很多方法,但都没有找到合适的方法。我试图找出如何在单行至少有两个相同的变量响应的情况下,通过编码响应向 Dataframe 添加新列。我的数据有42列,因此我包含了一个简短的示例,但我需要输出包含 Dataframe 所有列的任何响应。

ID<- c(1,2,3,4,5)
CV<- c("Detected", "Not Detected", "Detected", "Not Detected", "Detected")
RV<- c("Not Detected", "Detected", "Not Detected", "Detected", "Not Detected")
BP<- c("Detected", "Detected", "Not Detected", "Detected", "Detected")

我希望新列被称为“共感染”,如果每行有两个“检出”的观察结果响应,我希望新列指示“共感染”,如果只有一个“检出”的观察结果响应或所有均为“未检出”,则我希望列响应为“阴性”。因此,我希望它看起来像这样:

ID<- c(1,2,3,4,5)
CV<- c("Detected", "Not Detected", "Detected", "Not Detected", "Detected")
RV<- c("Not Detected", "Detected", "Not Detected", "Detected", "Not Detected")
BP<- c("Detected", "Detected", "Not Detected", "Detected", "Detected")

Coinfection<- c("Coinfection", "Coinfection", "Negative", "Coinfection", "Coinfection")

df<- data.frame(ID, CV, RV, BP, Coinfection)
    
ID          CV                RV               BP              Coinfection
1           Detected          Not Detected     Detected        Coinfection
2           Not Detected      Detected         Detected        Coinfection
3           Detected          Not Detected     Not Detected    Negative
4           Not Detected      Detected         Detected        Coinfection
5           Detected          Not Detected     Detected        Coinfection
rxztt3cl

rxztt3cl1#

df$Coinfection <- ifelse(rowSums(df == "Detected", na.rm = TRUE) >= 2, "Coinfection", "Negative"))

相关问题