在 dplyr 中重复 data.frame 的行 [英] Repeating rows of data.frame in dplyr
问题描述
我在使用 dplyr
重复我的真实数据行时遇到问题.这里已经有另一篇文章repeat-rows-of-a-data-frame 但没有针对 dplyr
的解决方案.
I have a trouble with repeating rows of my real data using dplyr
. There is already another post in here repeat-rows-of-a-data-frame but no solution for dplyr
.
在这里,我只是想知道 dplyr
的解决方案如何但因错误而失败:
Here I just wonder how could be the solution for dplyr
but failed with error:
错误:错误的结果大小 (16),预期为 4 或 1
Error: wrong result size (16), expected 4 or 1
library(dplyr)
df <- data.frame(column = letters[1:4])
df_rep <- df%>%
mutate(column=rep(column,each=4))
预期输出
>df_rep
column
#a
#a
#a
#a
#b
#b
#b
#b
#*
#*
#*
推荐答案
如果 data.frame 有其他列(那里,我说过!),但是 do
块,这是充满危险的将允许您在 dplyr
管道中生成派生的 data.frame(尽管,ceci n'est pas un pipe):
This is rife with peril if the data.frame has other columns (there, I said it!), but the do
block will allow you to generate a derived data.frame within a dplyr
pipe (though, ceci n'est pas un pipe):
library(dplyr)
df <- data.frame(column = letters[1:4], stringsAsFactors = FALSE)
df %>%
do( data.frame(column = rep(.$column, each = 4), stringsAsFactors = FALSE) )
# column
# 1 a
# 2 a
# 3 a
# 4 a
# 5 b
# 6 b
# 7 b
# 8 b
# 9 c
# 10 c
# 11 c
# 12 c
# 13 d
# 14 d
# 15 d
# 16 d
正如@Frank 所建议的,一个更好的选择可能是
As @Frank suggested, a much better alternative could be
df %>% slice(rep(1:n(), each=4))
这篇关于在 dplyr 中重复 data.frame 的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!