首页 > 解决方案 > 为许多文件按单词聚合词向量包

问题描述

我目前有一个向量列表,其中列表中的每个数字代表文件中不同单词的计数。

我想将此列表更改为一个数据框,其中行名是文件名,列是单词(按字母顺序排序,每个单词只有一列),每个观察值都是某个单词的计数,其中所有单词都在任何文件被包含(即如果文件a包含文件b不包含的单词,则文件b中的单词计数为0)。

所以基本上现在的当前代码看起来像:


file1 <- c(1,5,7,2)
names(file1) <- c("a", "by", "her", "the")

file2 <- c(10,5,2)
names(file2) <- c("a", "and", "to")

list(file1, file2)

我想要的是:


df <- data.frame(matrix(nrow=2, ncol=6, byrow=T, data=c(1, 0, 5, 7, 2, 0,
                                                        10, 5, 0,0,0,2)))
colnames(df) <- c("a", "and", "by", "her", "the", "to")
rownames(df) <- c("file1", "file2")
df


谢谢。

标签: rdata-cleaning

解决方案


包中的函数fill参数在这里可以派上用场。rbindlistdata.table

library(data.table)

nm = c("file1", "file2")
d = rbindlist(lapply(mget(nm), function(x) data.frame(t(x))), fill = TRUE)
d = as.data.frame(d)
row.names(d) = nm
d
#       a by her the and to
#file1  1  5   7   2  NA NA
#file2 10 NA  NA  NA   5  2

要重新排序d和替换NA0,需要进一步的步骤

d = d[,order(colnames(d))]
d = replace(d, is.na(d), 0)

推荐阅读