对于一个特殊问题,我似乎有一个非常低效的解决方案。我有文本数据,由于各种原因,这些数据以随机间隔在数据帧的行中中断。然而,基于数据帧中其他变量的独特组合,已知某些子集属于一起。例如,请参阅展示结构和我的初始解决方案的 MWE:

# Data
df <- read.table(text="page passage  person index text
1  123   A   1 hello
1  123   A   2 my
1  123   A   3 name
1  123   A   4 is
1  123   A   5 guy
1  124   B   1 well
1  124   B   2 hello
1  124   B   3 guy",header=T,stringsAsFactors=F)

master<-data.frame()
for (i in 123:max(df$passage)) {
  print(paste0('passage ',i))
  tempset <- df[df$passage==i,]
  concat<-''
  for (j in 1:nrow(tempset)) {
    print(paste0('index ',j))
    concat<-paste(concat, tempset$text[j])
  }
  tempdf<-data.frame(tempset$page[1],tempset$passage[1], tempset$person[1], concat, stringsAsFactors = FALSE)
  master<-rbind(master, tempdf)
  rm(concat, tempset, tempdf)
}
master
> master
  tempset.page.1. tempset.passage.1. tempset.person.1.                concat
1               1                123                 A  hello my name is guy
2               1                124                 B        well hello guy

在这个例子中和我的实际情况一样,“passage”是唯一的分组变量,因此虽然我希望它们在我的数据集中可用,但并不完全需要将其他部分与它一起使用。

我目前的估计是,我设计的这个过程对于一个数据集需要几个小时,否则我的计算机上的 R 很容易处理。也许通过其他函数或包可以获得一些效率,或者不创建和删除这么多对象?

感谢您在这里的任何帮助!

最佳答案

这里有两种方法:

基 R

aggregate(
    text ~ page + passage + person,
    data=df,
    FUN=paste, collapse=' '
)

dplyr
library(dplyr)
df %>%
    group_by_(~page, ~passage, ~person) %>%
    summarize_(text=~paste(text, collapse=' '))

关于R Dataframe : aggregating strings within column, 跨行,按组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30266983/

10-12 21:39