我想执行某项操作,该操作将以所提供的格式转换数据:
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?
答案 0 :(得分:4)
我们可以将cSplit()
包中的splitstackshape
与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))
答案 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'的length
和sum
。
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))))