从推文创建稀疏矩阵

Create sparse matrix from tweets

我有一些推文和其他变量,我想将其转换为稀疏矩阵。

这基本上就是我的数据的样子。现在它保存在 data.table 中,其中一列包含推文,一列包含分数。

Tweet               Score
Sample Tweet :)        1
Different Tweet        0

我想将其转换成如下所示的矩阵:

Score Sample Tweet Different :)
    1      1     1         0  1
    0      0     1         1  0

我的 data.table 中的每一行在稀疏矩阵中都有一行。在 R 中有没有简单的方法来做到这一点?

这很接近你想要的

library(Matrix)
words = unique(unlist(strsplit(dt[, Tweet], ' ')))

M = Matrix(0, nrow = NROW(dt), ncol = length(words))
colnames(M) = words

for(j in 1:length(words)){
  M[, j] = grepl(paste0('\b', words[j], '\b'), dt[, Tweet])
}

M = cbind(M, as.matrix(dt[, setdiff(names(dt),'Tweet'), with=F]))

#2 x 5 sparse Matrix of class "dgCMatrix"
#     Sample Tweet :) Different Score
#[1,]      1     1  .         .     1
#[2,]      .     1  .         1     .

唯一的小问题是正则表达式无法将 ':)' 识别为单词。也许更了解正则表达式的人可以建议如何解决这个问题。