在基数 R 中:
cbind(df1, v = apply(df[-1], 1, \(x)toString(names(df1)[-1][x==1])))
Specimen.ID FLUA FLUB RSV HMPV v
1 1 1 0 1 0 FLUA, RSV
2 2 0 1 1 0 FLUB, RSV
3 3 0 1 1 1 FLUB, RSV, HMPV
aggregate(cbind(virus_combination = as.character(ind)) ~ Specimen.ID,
cbind(df1['Specimen.ID'], stack(df1, -Specimen.ID)),
toString, subset = values > 0 ) |>
merge(df1, y = _)
Specimen.ID FLUA FLUB RSV HMPV virus_combination
1 1 1 0 1 0 FLUA, RSV
2 2 0 1 1 0 FLUB, RSV
3 3 0 1 1 1 FLUB, RSV, HMPV
a <- as.matrix(df[-1])
cbind(df, v = tapply(names(df)[(a * col(a)) + 1], a*row(a), toString)[-1])
Specimen_ID FLUA FLUB RSV HMPV v
1 1 1 0 1 0 FLUA, RSV
2 2 0 1 1 0 FLUB, RSV
3 3 0 1 1 1 FLUB, RSV, HMPV