我有一个看起来非常低效的解决方案,用于解决一个奇特的问题。我有文本数据,由于各种原因,在数据帧的行之间以随机间隔分裂。然而,基于数据帧中其他变量的唯一组合,某些子集是已知归属于一起的。例如,请参见演示结构和我的初始解决方案的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”是唯一的分组变量,因此并不完全需要将其他部分与其一起带出来,尽管我希望它们在我的数据集中可用。
我的目前估计是,我所设计的这个过程将花费几个小时来处理一个在我的电脑上很容易处理的数据集。也许可以通过其他函数或包获得一些效率,或者不要创建和删除那么多对象?
感谢任何帮助!
DT[, .(concat=paste0(...
这样数据表的答案就像其他答案一样有一个明确标记的列呢? - arvi1000