重复 data.frame 的行 N 次 [英] Repeat rows of a data.frame N times
问题描述
我有以下数据框:
data.frame(a = c(1,2,3),b = c(1,2,3))
a b
1 1 1
2 2 2
3 3 3
我想重复行 n 次.例如,这里的行重复了 3 次:
I want to repeat the rows n times. For example, here the rows are repeated 3 times:
a b
1 1 1
2 2 2
3 3 3
4 1 1
5 2 2
6 3 3
7 1 1
8 2 2
9 3 3
在 R 中有一个简单的函数可以做到这一点吗?谢谢!
Is there an easy function to do this in R? Thanks!
推荐答案
更新为更好的现代 R 答案.
updated to a better modern R answer.
您可以使用 replicate()
,然后 rbind
将结果重新组合在一起.行名会自动更改为从 1:nrows 开始运行.
You can use replicate()
, then rbind
the result back together. The rownames are automatically altered to run from 1:nrows.
d <- data.frame(a = c(1,2,3),b = c(1,2,3))
n <- 3
do.call("rbind", replicate(n, d, simplify = FALSE))
更传统的方法是使用索引,但这里的行名更改不是那么整洁(但提供更多信息):
A more traditional way is to use indexing, but here the rowname altering is not quite so neat (but more informative):
d[rep(seq_len(nrow(d)), n), ]
这里是对上面的改进,前两个使用purrr
函数式编程,惯用的purrr:
Here are improvements on the above, the first two using purrr
functional programming, idiomatic purrr:
purrr::map_dfr(seq_len(3), ~d)
和不那么惯用的呼噜声(相同的结果,虽然更尴尬):
and less idiomatic purrr (identical result, though more awkward):
purrr::map_dfr(seq_len(3), function(x) d)
最后使用dplyr
通过索引而不是列表应用:
and finally via indexing rather than list apply using dplyr
:
d %>% slice(rep(row_number(), 3))
这篇关于重复 data.frame 的行 N 次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!