我有两个列表。第一个包含每个元素的字符串。第二个列表的每个元素都有一个数据框。数据框有一个“开始”列和另一个“结束”列以及其他信息。
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 中使用来提取文本。
对于单个文本元素,我可以使用下面的循环,然后将其添加到特征数据框中。
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 问题,但似乎找不到解决此问题的方法。
目标是获得一个特征列表,其中附加了提取的术语,就像我对上面的单个循环所做的那样。感谢您的帮助。
最佳答案
与双 for 循环等效的是使用 Map
并将两个相应列表作为参数传递。然后,您可以利用 substring
被矢量化的事实来进行最终提取。
Map(function(tex,fea) substring(tex, fea$start, fea$end), all.text, all.features)
#[[1]]
#[1] "th" "is " " is a" "s a lo"
#
#[[2]]
#[1] "an" "oth" "her p" "r piec"
#
#[[3]]
#[1] "ent" "nt" "en" "ce o"
关于R 两个列表上的 substr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38649400/