我有一个数据框,想要从中缩小范围:
对此:
library(tidyverse)
df %>%
gather(key, val, -ID) %>%
filter(val == 1) %>%
select(-val) %>%
group_by(ID) %>%
mutate(ind = paste0("Music", row_number())) %>%
spread(ind, key) %>%
right_join(df) %>%
select(names(df), everything())
# A tibble: 6 x 8
# Groups: ID [6]
# ID Pop Jazz Classical Rap Music1 Music2 Music3
# <fct> <fct> <fct> <fct> <fct> <chr> <chr> <chr>
#1 1 1 1 0 1 Pop Jazz Rap
#2 2 0 0 0 1 Rap <NA> <NA>
#3 3 1 0 1 1 Pop Classical Rap
#4 4 0 1 0 0 Jazz <NA> <NA>
#5 5 0 1 0 1 Jazz Rap <NA>
#6 6 0 0 0 0 <NA> <NA> <NA>
是否有一种 tidyverse 式的方式而不使用多个'and'操作?
答案 0 :(得分:1)
使用longSequences
代替&&
&