R语言 如何汇总列中的响应以基于列标题创建新响应?[duplicate]

v8wbuo2f  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(154)
    • 此问题在此处已有答案**:

For each row, get column names where data is equal to a certain value(3个答案)
3天前关闭。
我的数据如下所示

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")
FL<- c("Detected", "Detected", "Not Detected", "Detected", "Detected")

df<- data.frame(ID, CV, RV, BP, FL)

我想合并每个观测中的"检出"响应,并创建一个新列,给出每个检出响应的列名,如下所示

ID          CV                RV               BP              FL             Result
1           Detected          Not Detected     Detected        Detected       CV, BP, FL
2           Not Detected      Detected         Detected        Detected       RV, BP, FL
3           Detected          Not Detected     Not Detected    Not Detected   CV
4           Not Detected      Detected         Detected        Detected       RV, BP, FL
5           Detected          Not Detected     Detected        Detected       CV, BP, FL
a11xaf1n

a11xaf1n1#

我们可以使用cur_column()来标识与条件相结合的列名。使用unite将把它们放在一起:

library(dplyr)
library(tidyr)

df %>% 
  mutate(across(-ID, ~case_when(. == "Detected" ~ cur_column()), .names = 'new_{col}')) %>%
  unite(Result, starts_with('new'), na.rm = TRUE, sep = ' ')
ID           CV           RV           BP           FL   Result
1  1     Detected Not Detected     Detected     Detected CV BP FL
2  2 Not Detected     Detected     Detected     Detected RV BP FL
3  3     Detected Not Detected Not Detected Not Detected       CV
4  4 Not Detected     Detected     Detected     Detected RV BP FL
5  5     Detected Not Detected     Detected     Detected CV BP FL

相关问题