【问题标题】:R substr on two lists两个列表上的 R substr
【发布时间】: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 问题,但似乎找不到解决方法。

目标是获得一个特征列表,其中附加了提取的术语,就像我在上面的单个循环中所做的那样。感谢您提供任何帮助。

【问题讨论】:

    标签: r loops substring


    【解决方案1】:

    双循环的等价物是使用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"
    

    【讨论】:

    • 出于我自己的好奇,是否可以将这些输出添加到相应的位置?我的意思是我们可以将#[1] "th" "is " " is a" "s a lo" 添加到all.features[[1]] 和其他类似的。
    • @user2100721 - 当然 - 类似Map(function(tex,fea) cbind(fea, string=substring(tex, fea$start, fea$end)), all.text, all.features)
    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 1970-01-01
    相关资源
    最近更新 更多