r - 为许多文件按单词聚合词向量包
问题描述
我目前有一个向量列表,其中列表中的每个数字代表文件中不同单词的计数。
我想将此列表更改为一个数据框,其中行名是文件名,列是单词(按字母顺序排序,每个单词只有一列),每个观察值都是某个单词的计数,其中所有单词都在任何文件被包含(即如果文件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
谢谢。
解决方案
包中的函数fill
参数在这里可以派上用场。rbindlist
data.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
和替换NA
为0
,需要进一步的步骤
d = d[,order(colnames(d))]
d = replace(d, is.na(d), 0)
推荐阅读
- pandas - pandas-选择与特定索引对应的数据框列
- r - 使用 R 软件与 MatLab 中的 3D 矩阵相关
- angular2-directives - 访问指令状态并填充 ngFor
- css - 为什么这个极其简单的 CSS 代码没有达到预期的效果?
- c# - Datagridview 仅显示最后一条记录,尽管在比较 currentreading excel 和发票表时我有更多行
- c++ - 如何在 C++ 中拆分没有 stringstream 和 strtok 的字符串(提取单词)?
- reactjs - AppBar中左右对齐的图标都带有material-ui next
- ios - 尝试使用 FileManager 移动项目时出错
- html - 间距调整
行标签 - python - 如何在 Python 井字游戏中切换玩家