我正在尝试转换类似这样的 df
格式:
df <- data.frame(first = c("a", "a", "b", "b", "b", "c"),
words =c("about", "among", "blue", "but", "both", "cat"))
df
first words
1 a about
2 a among
3 b blue
4 b but
5 b both
6 c cat
转换成如下格式:
df1
first words
1 a about, among
2 b blue, but, both
3 c cat
>
我试过了
aggregate(words ~ first, data = df, FUN = list)
first words
1 a 1, 2
2 b 3, 5, 4
3 c 6
和tidyverse
:
df %>%
group_by(first) %>%
group_rows()
如有任何建议,我们将不胜感激!
最佳答案
一个data.table
解决方案:
library(data.table)
df <- data.frame(first = c("a", "a", "b", "b", "b", "c"),
words =c("about", "among", "blue", "but", "both", "cat"))
df <- setDT(df)[, lapply(.SD, toString), by = first]
df
# first words
# 1: a about, among
# 2: b blue, but, both
# 3: c cat
# convert back to a data.frame if you want
setDF(df)
关于r - 组织子组字符串(文本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460117/