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"
In the Copy and insert rows & columns dialog box, select Copy and insert rows option in the Type section, then select the data range you want to duplicate, and then specify the repeat time to duplicate the rows, see screenshot: 4.
In Python, if you want to repeat the elements multiple times in the NumPy array then you can use the numpy. repeat() function. In Python, this method is available in the NumPy module and this function is used to return the numpy array of the repeated items along with axis such as 0 and 1.
Method 1 : Using replicate() method The rbind() method is taken as the first argument of this method to combine data frames together. The second argument is the replicate() method which is used to create multiple copies of the rows of the data frames equivalent to the number of times same as replication factor.
df <- data.frame(a = 1:2, b = letters[1:2]) df[rep(seq_len(nrow(df)), each = 2), ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With