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.
Example for 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
So, each row is repeated 2 times and characters remain characters, factors remain factors, numerics remain numerics, ...
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"
n.times <- c(2,4) ; df[rep(seq_len(nrow(df)), n.times),]
if you want to vary the number of times each line is repeated. – Mythify