首页 > 解决方案 > 为 Table() 或 Tibble() 创建向量而不是列,为 Vector by Row Word Occurrence Table r

问题描述

我有一个包含约 30,000 个字符串作为元素的向量(每个大约 30 个字符)。这是一个例子:

OriginalVector <- c("nimble red fox", "lazy grey dog", "red fox funny")

我需要一种将这些字符串转换为单词出现表的方法。元素中给定单词的出现用 1(或其他整数)表示。此信息需要针对向量中的其他字符串进行交叉引用。

解决方案1:

table(unnest_tokens(df, word, text))

输出解决方案1:

id  dog fox funny grey lazy nimble red
  1   0   1     0    0    0      1   1
  2   1   0     0    1    1      0   0
  3   0   1     1    0    0      0   1

解决方案2:

df %>%
  unnest_tokens(word, text) %>%
  count(id, word) %>%
  pivot_wider(id_cols = id, names_from = word, 
              values_from = n, values_fill = list(n = 0)) %>%
  select(-id)

输出解决方案2:

    fox nimble   red   dog  grey  lazy funny
  <int>  <int> <int> <int> <int> <int> <int>
1     1      1     1     0     0     0     0
2     0      0     0     1     1     1     0
3     1      0     1     0     0     0     1

不幸的是,我需要向量来代替列。这样:

fox <- c(1, 0, 1)
nimble <- c(1, 0, 0)

解决方案 1 或解决方案 2 有没有办法做到这一点?最好是解决方案 1,因为它占用的资源较少。

标签: rstringvector

解决方案


推荐阅读