如何根据键对名称进行分组,是否在tidyverse中使用spread
函数?
example <- tribble(
~key, ~names,
"t1", "name1",
"t1", "name2",
"t2", "name3",
"t2", "name4",
"t4", "name5"
)
example %>% spread(key, names)
Error: Duplicate identifiers for rows (1, 2), (3, 4)
desired output
t1 name1,name2
t2 name3,name4
t4 name5
答案 0 :(得分:2)
spread
用于旋转/重塑表,通常需要三列(id列,标题列和值列)来提供有意义的结果;要获得所需的输出,您可以按键进行分组,并将名称汇总到列表中:
example %>%
group_by(key) %>%
summarise(names = list(names)) %>%
as.data.frame() # for print purpose only
# key names
#1 t1 name1, name2
#2 t2 name3, name4
#3 t4 name5
或者可能是双向表:
table(example)
# names
#key name1 name2 name3 name4 name5
# t1 1 1 0 0 0
# t2 0 0 1 1 0
# t4 0 0 0 0 1