r中的字频率计数器

时间:2016-04-08 07:54:52

标签: r frequency word text-analysis

我想执行某项操作,该操作将以所提供的格式转换数据:

输入:

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?

2 个答案:

答案 0 :(得分:4)

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

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))

答案 1 :(得分:1)

以下是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',使用lengths选项,通过'lst'的list输出的data.frame复制'Col_B',以创建{{1}然后使用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))))