【问题标题】:R lapply using stringi and rbindR lapply 使用 stringi 和 rbind
【发布时间】:2016-09-29 17:08:43
【问题描述】:

我想用特定的字符串分割数据框中的一些数据并计算频率。

玩弄了几种方法后,我想出了一个方法,但结果有一点错误。

例子:

数据框数据文件:

data
abc hello
hello
aaa
zxy
xyz

列表:

list
abc
bcd
efg
aaa

我的代码:

lapply(list$list, function(x){
    t <- data.frame(words = stri_extract(df$data, coll=x))
    t<- setDT(t)[, .( Count = .N), by = words]
    t<-t[complete.cases(t$words)]
    result<-rbind(result,t)
    write.csv(result, "new.csv", row.names = F)
})

在此示例中,我希望 CSV 文件具有以下结果:

words Count
abc     1
aaa     1

但是我得到了我的代码:

words Count
aaa     1

我知道stri_extract 应该在abc hello 中识别abc,所以当我使用rbind 时可能会发生错误?

【问题讨论】:

  • 另见:stringi::stri_list2matrix

标签: r lapply rbind stringi


【解决方案1】:

您需要将write.csv 文件移出循环,否则它将覆盖先前保存的文件,您将只能在最后阶段保存文件。通过这样做,您将不得不在lapply 之外使用rbind 您的结果,因为您不能在函数中修改result 变量。

result <- do.call(rbind, lapply(list$list, function(x){
                                t <- data.frame(words = stri_extract(df$data, coll=x))
                                t<- setDT(t)[, .( Count = .N), by = words]
                                t<-t[complete.cases(t$words)]
                                t
 }))

write.csv(result, "new.csv", row.names = F)

【讨论】:

  • 谢谢,很有帮助
  • 你不能在 append=T 的循环中包含 write.csv 吗?反正这可能只会减慢进程,我只需要写一次,问一下就行了
  • 这也是一个可行的解决方案。你可以继续尝试。不确定性能。
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多