我在处理R中的数据帧时遇到问题.我想根据另一列中单元格的值将单元格的内容粘贴到不同的行中.我的问题是我希望逐步(累积)打印输出.输出向量必须与输入向量的长度相同.这是一个类似于我正在处理的样本表:
id <- c("a", "a", "a", "b", "b", "b")
content <- c("A", "B", "A", "B", "C", "B")
(testdf <- data.frame(id, content, stringsAsFactors=FALSE))
# id content
#1 a A
#2 a B
#3 a A
#4 b B
#5 b C
#6 b B
Run Code Online (Sandbox Code Playgroud)
这是希望我希望结果看起来像:
result <- c("A", "A B", "A B A", "B", "B C", "B C B")
result
#[1] "A" "A B" "A B A" "B" "B C" "B C B"
Run Code Online (Sandbox Code Playgroud)
我不需要这样的东西:
ddply(testdf, .(id), summarize, content_concatenated = paste(content, collapse = " "))
# id content_concatenated
#1 a A B A
#2 b B C B
Run Code Online (Sandbox Code Playgroud)
ale*_*laz 29
您可以使用以下命令定义"累积粘贴"功能Reduce:
cumpaste = function(x, .sep = " ")
Reduce(function(x1, x2) paste(x1, x2, sep = .sep), x, accumulate = TRUE)
cumpaste(letters[1:3], "; ")
#[1] "a" "a; b" "a; b; c"
Run Code Online (Sandbox Code Playgroud)
Reduce循环避免了从开始重新连接元素,因为它延长了下一个元素的先前串联.
按组应用:
ave(as.character(testdf$content), testdf$id, FUN = cumpaste)
#[1] "A" "A B" "A B A" "B" "B C" "B C B"
Run Code Online (Sandbox Code Playgroud)
另一个想法是,可以在开始时连接整个向量,然后逐步substring:
cumpaste2 = function(x, .sep = " ")
{
concat = paste(x, collapse = .sep)
substring(concat, 1L, cumsum(c(nchar(x[[1L]]), nchar(x[-1L]) + nchar(.sep))))
}
cumpaste2(letters[1:3], " ;@-")
#[1] "a" "a ;@-b" "a ;@-b ;@-c"
Run Code Online (Sandbox Code Playgroud)
这似乎也有点快:
set.seed(077)
X = replicate(1e3, paste(sample(letters, sample(0:5, 1), TRUE), collapse = ""))
identical(cumpaste(X, " --- "), cumpaste2(X, " --- "))
#[1] TRUE
microbenchmark::microbenchmark(cumpaste(X, " --- "), cumpaste2(X, " --- "), times = 30)
#Unit: milliseconds
# expr min lq mean median uq max neval cld
# cumpaste(X, " --- ") 21.19967 21.82295 26.47899 24.83196 30.34068 39.86275 30 b
# cumpaste2(X, " --- ") 14.41291 14.92378 16.87865 16.03339 18.56703 23.22958 30 a
Run Code Online (Sandbox Code Playgroud)
......这就是它cumpaste_faster.
data.table解决方案
library(data.table)
setDT(testdf)[, content2 := sapply(seq_len(.N), function(x) paste(content[seq_len(x)], collapse = " ")), by = id]
testdf
## id content content2
## 1: a A A
## 2: a B A B
## 3: a A A B A
## 4: b B B
## 5: b C B C
## 6: b B B C B
Run Code Online (Sandbox Code Playgroud)
这是一种ddply使用子集sapply以增量方式粘贴在一起的方法:
library(plyr)
ddply(testdf, .(id), mutate, content_concatenated = sapply(seq_along(content), function(x) paste(content[seq(x)], collapse = " ")))
id content content_concatenated
1 a A A
2 a B A B
3 a A A B A
4 b B B
5 b C B C
6 b B B C B
Run Code Online (Sandbox Code Playgroud)