r中的词频计数器

word frequency counter in r

我想执行某个操作,以提供的格式转换数据:

输入:

Col_A                         Col_B
textA textB                     10
textB textC                     20
textC textD                     30
textD textE                     40
textE textF                     20

操作:

ColA           ColB(Frequency)            ColC
textA                  1                    10
textB                  2                  10+20
textC                  2                  20+30
textD                  2                  30+40
textE                  2                  40+20
textF                  1                    20

输出:

  ColA           ColB(Frequency)            ColC
    textA                  1                  10
    textB                  2                  30
    textC                  2                  50
    textD                  2                  70
    textE                  2                  60
    textF                  1                  20

目前我正在使用

k <- (dfm(A2$Query, ngrams = 1, concatenator = " ", verbose = FALSE))
k <- colSums(k)
k <- as.data.frame(k)

这给了我频率列。如何实现colC?

我们可以将 splitstackshape 包中的 cSplit()dplyr 结合使用。

library(splitstackshape)
library(dplyr)
cSplit(df, "Col_A", sep = " ", direction = "long") %>% 
  group_by(Col_A) %>%
  summarise(Freq = n(), ColC = sum(Col_B))
#   Col_A  Freq  ColC
#  (fctr) (int) (int)
#1  textA     1    10
#2  textB     2    30
#3  textC     2    50
#4  textD     2    70
#5  textE     2    60
#6  textF     1    20

数据

df <- structure(list(Col_A = structure(1:5, .Label = c("textA textB", 
"textB textC", "textC textD", "textD textE", "textE textF"), class = "factor"), 
    Col_B = c(10L, 20L, 30L, 40L, 20L)), .Names = c("Col_A", 
"Col_B"), class = "data.frame", row.names = c(NA, -5L))

这是另一个选项 separate/gather

library(dplyr)
library(tidyr)
separate(df1, Col_A, into = c("Col_A1", "Col_A2")) %>%
         gather(Var, ColA, -Col_B) %>%
         group_by(ColA) %>%
         summarise(Freq=n(),Col_C= sum(Col_B))
#   ColA  Freq Col_C
#  (chr) (int) (int)
#1 textA     1    10
#2 textB     2    30
#3 textC     2    50
#4 textD     2    70
#5 textE     2    60
#6 textF     1    20

或使用 base R 选项,将 'Col_A' 拆分为 space,通过 list 输出的 lengths 复制 'Col_B'从 'lst' 创建一个 data.frame 然后使用 aggregate 得到 'Col_B'.

lengthsum
lst <- strsplit(df1$Col_A, " ")
d1 <- data.frame(Col_A= unlist(lst), Col_C=rep(df1$Col_B, lengths(lst)))
do.call(data.frame, aggregate(.~Col_A, d1, function(x) c(length(x), sum(x))))