【问题标题】:CountVectorizer in R not fitting all the words into the bagR中的CountVectorizer无法将所有单词都放入包中
【发布时间】:2019-03-18 21:56:52
【问题描述】:

我有一个这样的数据框:

    id                 words
 1:  1          capuccin,mok
 2:  2 bimboll,ext,sajonjoli
 3:  3          burrit,sincr
 4:  4  div,tir,mini,doradit
 5:  5   pan,multigran,linaz
 6:  6         tost,integral
 7:  7             pan,blanc
 8:  8  sup,pan,bco,ajonjoli
 9:  9                  wond
10: 10                  wond

我正在使用以下代码:

bag_of_words <- CountVectorizer$new()
result_df <- cbind(df$id, bag_of_words$fit_transform(df$words))

我想要这样的东西:

   tab_1$id capuccin mok bimboll ext sajonjoli...
1         1        1   1       0   0         0...
2         2        0   0       1   1         1...
3         3        0   0       0   0         0...
4       ...      ... ...     ... ...       ...

但是,它返回一个包含每个单词出现次数的矩阵,它只是返回单词wond

   df$id wond
1         1    0
2         2    0
3         3    0
4         4    0
5         5    0
6         6    0
7         7    0
8         8    0
9         9    1
10       10    1

我的代码有什么问题?

【问题讨论】:

  • 不确定CountVectorizer 是如何工作的,但上面发布的链接可以使用mtabulatestrsplit 来获得相同的输出。
  • 使用dplyr 你可以试试df %&gt;% mutate(words = strsplit(words, ",")) %&gt;% unnest() %&gt;% count(words)

标签: r countvectorizer


【解决方案1】:

我通过使用一种比 cmets 中 tmfmnk 建议的方法更简单的方法得到了这一点。

tab_1 <- tab_1 %>%
  unnest(words) %>%
  mutate(words = strsplit(words, ','), occ = 1) %>%
  dcast(id ~ unlist(words), fill = 0)

现在它按预期工作了。

id ajonjoli bco bimboll ...
1         0   0       0 ...
2         0   0       1 ...
3         0   0       0 ...
...     ... ...     ...

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2018-05-22
    • 2022-07-08
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多