重复 data.frame 的行 [英] Repeat rows of a data.frame

查看:35
本文介绍了重复 data.frame 的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重复 data.frame 的行,每次 N 次.结果应该是一个新的 data.frame(带有 nrow(new.df) == nrow(old.df) * N)保持列的数据类型.

I want to repeat the rows of a data.frame, each N times. The result should be a new data.frame (with nrow(new.df) == nrow(old.df) * N) keeping the data types of the columns.

N = 2 的示例:

                        A B   C
  A B   C             1 j i 100
1 j i 100     -->     2 j i 100
2 K P 101             3 K P 101
                      4 K P 101

所以,每行重复 2 次,字符仍然是字符,因子仍然是因子,数字仍然是数字,......

So, each row is repeated 2 times and characters remain characters, factors remain factors, numerics remain numerics, ...

我第一次尝试使用 apply:apply(old.df, 2, function(co) rep(co, each = N)),但是这个将我的值转换为字符,我得到:

My first attempt used apply: apply(old.df, 2, function(co) rep(co, each = N)), but this one transforms my values to characters and I get:

     A   B   C    
[1,] "j" "i" "100"
[2,] "j" "i" "100"
[3,] "K" "P" "101"
[4,] "K" "P" "101"

推荐答案

df <- data.frame(a = 1:2, b = letters[1:2]) 
df[rep(seq_len(nrow(df)), each = 2), ]

这篇关于重复 data.frame 的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆