r-将函数转换为apply,sapply(data.frame)



所以我刚刚构建了这个函数,它基本上接受两个字符串(一个文本和一组关键字)。然后,它必须找到文本字符串中包含的关键字数量(如果有的话)。我一直试图将代码应用于数据帧,但没有成功。

功能正在工作:

something=function(text,keywords){
  kw = unlist(strsplit(keywords, ","))
  c=0
  for(i in length(kw)){
    if(grepl(kw[i],text)==0){
      c=c+1
    } else {c}
  }
  return(c)
}

如果我输入:

> something("this planetarium is the shit","planetarium,amazing")
[1] 1

但是如果我的数据帧是df

     keyword         text_clean
1    planetarium     Man this planetarium is the shit
2 musee,africain     rt lyonmangels reste encore places franceangels tour lyon organisons  investissons pme

我的预期输出是:

  df.1
1  1
2  0

有什么见解吗?我正在尝试这个代码:

substng<-function(text, keywords){
  vector = laply(text,function(text,keywords){
    kw = unlist(strsplit(keywords, ","))
    c=0
    for(i in length(kw)){
      if(grepl(kw[i],text)==0){
        c=c+1
      } else {c}
    }
    return(c)
  })
  vector.df= as.data.frame(vector)
}
df <- read.table(header = TRUE, stringsAsFactors = FALSE, text = "keyword         text_clean
planetarium     'Man this planetarium is the shit'
musee,africain     'rt lyonmangels reste encore places franceangels tour lyon organisons  investissons pme'")
df$count = substng(df$text_clean,df$keyword)

我认为stringi包中的stri_count可以实现这一点。

使用"pattern|amazing"作为pattern/regex。管道="或"。

https://cran.r-project.org/web/packages/stringi/stringi.pdf

最新更新