可以使用dplyr
包中的tidyverse
函数来实现。具体步骤如下:
tidyverse
包:install.packages("tidyverse")
library(tidyverse)
df
,其中包含多列需要按条件堆叠。以下是一个示例数据框:df <- data.frame(
ID = c(1, 2, 3),
Cond1 = c("A", "B", "A"),
Col1 = c(10, 20, 30),
Cond2 = c("B", "A", "B"),
Col2 = c(40, 50, 60),
Cond3 = c("A", "A", "B"),
Col3 = c(70, 80, 90)
)
tidyverse
函数进行条件堆叠。以下是一个示例代码,将满足条件"A"的列堆叠在一起:df_stacked <- df %>%
select(starts_with("Col")) %>%
mutate(Condition = case_when(
Cond1 == "A" ~ "Col1",
Cond2 == "A" ~ "Col2",
Cond3 == "A" ~ "Col3"
)) %>%
group_by(ID) %>%
summarise(Stacked_Col = paste0(Condition, collapse = ", "))
在上述示例中,我们首先使用select()
函数选择需要堆叠的列(这里选择以"Col"开头的列)。然后,使用mutate()
函数根据条件创建新的列"Condition",将满足条件"A"的列名存储在其中。接下来,使用group_by()
函数按照"ID"列进行分组。最后,使用summarise()
函数将每组中满足条件"A"的列名连接在一起,结果存储在"Stacked_Col"列中。
以上就是在R中按条件堆叠多列的方法。使用这种方法,你可以根据自己的实际需求来修改条件和数据框的结构。
领取专属 10元无门槛券
手把手带您无忧上云