R:计算数据框中列表中单词的出现

R: calculate occurence of words from a list in data frame

我有一个包含 Categorypd 的数据框。我需要计算所有 pd 中每个有意义的词在每个 Category 中出现了多少次。我坚持最后一步 - 总结。理想情况下,该频率与 pd 乘以 Category 的总长度之比将是另一个 X 列。

示例:

freq = structure(list(Category = c("C1", "C2"
), pd = c("96 oz, epsom salt 96 oz, epsom bath salt", 
          "17 x 24 in, bath mat")), .Names = c("Category", "pd"), row.names = c(NA, 
                                                                                -2L), class = "data.frame")

pool = sort(unique(gsub("[[:punct:]]|[0-9]","", unlist(strsplit(freq[,2]," ")))))
pool = pool[nchar(pool)>1]

freq:

    Category    pd
1   C1  96 oz, epsom salt 96 oz, epsom bath salt
2   C2  17 x 24 in, bath mat

pool:

[1] "bath"  "epsom" "in"    "mat"   "oz"    "salt" 

期望的输出:

pool C1freq C1ratio C2freq C2ratio
bath 1 1/7 1 1/3
epsom 2 2/7 0 0
in 0 0 1 1/3
mat 0 0 1 1/3
oz 2 2/7 0 0
salt 2 2/7 0 0

在哪里,例如7C1[,2] 的长度,去掉了数字和标点符号(如 pool 规则)。 1/7当然不需要这种形式-这里只是为了显示分母长度。

如果可能,w/o dplyrqdap。谢谢!!

我们可以试试

library(qdapTools)
library(stringr)
lst <- str_extract_all(freq$pd, '[A-Za-z]{2,}')
m1 <- t(mtabulate(lst))
m2 <-  prop.table(m1,2)
cbind(m1, m2)[,c(1,3,2,4)]

或没有 qdapTools,

 Un1 <- sort(unique(unlist(lst)))
 m1 <- do.call(cbind, lapply(lst, function(x)
            table(factor(x, levels=Un1))))
 colnames(m1) <- freq$Category
 cbind(m1, `colnames<-`(prop.table(m1,2), paste0(colnames(m1), 'Prop')))

您可以考虑按以下方式调整当前方法:

tab <- table(
  stack(
    setNames(
      lapply(strsplit(gsub("[[:punct:]]|[0-9]", "", freq$pd), "\s+"), 
             function(x) x[nchar(x) > 1]), freq$Category)))

这里注意我是先用了gsub,而不是拆分后。然后,我在 space 上拆分,并按照您过滤数据的相同方式过滤数据。最后,我使用了 setNames,这样我就可以使用 stack 来得到一个可以制成表格的长 data.frame

数据制成表格后,只需使用 prop.table 即可获得所需的输出。

cbind(tab, prop.table(tab, 2))
#       C1 C2        C1        C2
# bath   1  1 0.1428571 0.3333333
# epsom  2  0 0.2857143 0.0000000
# in     0  1 0.0000000 0.3333333
# mat    0  1 0.0000000 0.3333333
# oz     2  0 0.2857143 0.0000000
# salt   2  0 0.2857143 0.0000000