【发布时间】:2016-12-03 14:45:48
【问题描述】:
我有两个列表。第一个有每个元素的字符串。第二个列表具有每个元素的数据框。数据框有一个列“开始”和另一个“结束”,以及其他信息。
text<-'this is a long text. its not an email'
text0<-'another piece of text'
text1<-'last sentence of nonsense'
all.text<-list(text,text0,text1)
features1<-data.frame(start=c(1,3,5,7),end=c(2,5,9,12),type=c('na','person','person','location'))
features2<-data.frame(start=c(1,3,5,7),end=c(2,5,9,12),type=c('na','person','person','location'))
features3<-data.frame(start=c(7,8,10,12),end=c(9,9,11,15),type=c('na','person','person','location'))
all.features<-list(features1,features2, features3)
我希望循环第一个文本元素和第一个数据框。可以在 substr 中使用数据框的列 start 和 end 来提取文本。
对于单个文本元素,我可以使用下面的循环,然后将其添加到要素数据框中。
one.text<-NULL
for (i in 1:nrow(features1)) one.text[i]<-((substr(text,features1[i,1],features1[i,2])))
features1$word<-one.text
但是我找不到使用 lapply 或嵌套循环的方法。显然,如果可能的话,我不想使用循环,因为我读到它们效率低下。我尝试过的一些事情:
named.get<-function(text.list,features.list){
named.entities<-substr(text.list,features.list[,1],features.list[,2])
}
all<-sapply(all.text,named.get,all.features)
或者嵌套循环
one.obj<-NULL
two.obj<-NULL
for(i in 1:length(all.text)){
for (j in 1:length(all.features)){
one.obj[j]<-list([i]<-((substr(all.text[i],all.features[[i]][j,1],all.features[[i]][j,2]))))
}
}
但这也没有用。我已经阅读了 substr 小插图,阅读了多个 stackoverflow 问题,但似乎找不到解决方法。
目标是获得一个特征列表,其中附加了提取的术语,就像我在上面的单个循环中所做的那样。感谢您提供任何帮助。
【问题讨论】: