R lapply using stringi and rbind



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

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

例:

数据

框数据文件:

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 时可能会发生错误?

您需要

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)

最新更新