我正在改变调查结果,包括多项选择回复.原始数据如下所示:
df <- data_frame(
id = c("a", "b", "c"),
tired = c(T, F, T),
lonely = c(F, F, T),
excited = c(F, T, T)
)
df
# A tibble: 3 x 4
id tired lonely excited
<chr> <lgl> <lgl> <lgl>
1 a TRUE FALSE FALSE
2 b FALSE FALSE TRUE
3 c TRUE TRUE TRUE
Run Code Online (Sandbox Code Playgroud)
我想创建一个新的列"感受",其中包含受访者表达的感受的逗号分隔值:
id feelings
<chr> <chr>
1 a tired, excited
2 b excited
3 c tired, lonely, excited
Run Code Online (Sandbox Code Playgroud)
中间步骤是将TRUE值替换为列的相应名称,以便产生:
id tired lonely excited
<chr> <lgl> <lgl> <lgl>
1 a tired excited
2 b excited
3 c tired lonely excited
Run Code Online (Sandbox Code Playgroud)
对于单个列,这很简单.但是,与示例不同,我的数据框中有很多列(10+,通常不超过一个或两个TRUE值),因此我想为多个列自动执行此操作.一种解决方案可能是循环遍历列并使用基本子集和替换,但是还有一种优雅的dplyr/tidy方法吗?
谢谢你的帮助!
一个选项是使用tidyr::gather然后总结使用dplyr:
library(dplyr)
library(tidyr)
df %>% gather(feelings, value, -id) %>% #Change to long format
filter(value) %>% #Filter for value which are TRUE
group_by(id) %>%
summarise(feelings= paste0(feelings,collapse=","))
# id feelings
# <chr> <chr>
# 1 a tired
# 2 b excited
# 3 c tired,lonely,excited
Run Code Online (Sandbox Code Playgroud)