我试图将来自同一用户的文本数据粘贴到一起,该用户当前按名称组织在不同的行中:
df <- read.table(header = TRUE, text = 'name text
"katy" "tomorrow I go"
"lauren" "and computing"
"katy" "to the store"
"stephanie" "foo and foos"')
Run Code Online (Sandbox Code Playgroud)
结果是:
df2 <- read.table(header=TRUE, text='name text
"katy" "tomorrow I go to the store"
"lauren" "and computing"
"stephanie" "foo and foos"')
Run Code Online (Sandbox Code Playgroud)
建议?
我们可以对“名称”分组的“文本”列使用data.table或dplyr或。使用之前,我们将'data.frame'转换为'data.table'()。aggregatepastedata.tablesetDT(df)
library(data.table)
setDT(df)[, list(text=paste(text, collapse=' ')), by = name]
Run Code Online (Sandbox Code Playgroud)
使用 dplyr
library(dplyr)
df %>%
group_by(name) %>%
summarise(text=paste(text, collapse=' '))
Run Code Online (Sandbox Code Playgroud)
或搭配 base R
aggregate(text~name, df, FUN= paste, collapse=' ')
Run Code Online (Sandbox Code Playgroud)