Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R repeat elements of data frame

I have searched the internet, but I haven't been able to find a solution to my problem. I have a data frame of numbers and characters:

mydf <- data.frame(col1=c(1, 2, 3, 4), 
                   col2 = c(5, 6, 7, 8), 
                   col3 = c("a", "b", "c", "d"), stringsAsFactors  = FALSE)

mydf:

col1 col2 col3
  1    5   a
  2    6   b
  3    7   c
  4    8   d

I would like to repeat this into

col1 col2 col3
  1   5    a
  1   5    a
  1   5    a
  2   6    b
  2   6    b
  2   6    b
  3   7    c
  3   7    c
  3   7    c
  4   8    d
  4   8    d
  4   8    d

Using apply(mydf, 2, function(x) rep(x, each = 3)) will give the right repetition, but will not conserve the classes of col1, col2, and col3, as numeric, numeric and character, respectively, as I would like. This is a constructed example, and setting the classes of each column in my data frame is a bit tedious.

Is there a way to make the repetition while conserving the classes?

like image 732
Sisse Avatar asked Jan 04 '12 12:01

Sisse


2 Answers

It's even easier than you think.

index <- rep(seq_len(nrow(mydf)), each = 3)
mydf[index, ]

This also avoids the implicit looping from apply.

like image 78
Richie Cotton Avatar answered Oct 13 '22 01:10

Richie Cotton


This is an unfortunate and an unexpected class conversion (too me, anyway). Here's an easy workaround that uses the fact that a data.frame is just a special list.

data.frame(lapply(mydf, function(x) rep(x, each = 3)))

(anyone know why the behaviour the questioner observed shouldn't be reported as a bug?)

like image 44
John Avatar answered Oct 12 '22 23:10

John