Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat rows of a data.frame [duplicate]

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" 
like image 615
Stefan Avatar asked Jun 20 '12 14:06

Stefan


People also ask

How do you duplicate rows and times?

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.

How do you repeat a row multiple times in python?

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.

How do you replicate data frames?

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.


1 Answers

df <- data.frame(a = 1:2, b = letters[1:2])  df[rep(seq_len(nrow(df)), each = 2), ] 
like image 101
Josh O'Brien Avatar answered Oct 01 '22 15:10

Josh O'Brien