Search code examples
rdataframematrixvectordatacolumn

Is there an easy way to create a data frame in R with the same vector repeating itself "n" times (as n coumns)?


I think the title says it all Let's jump to the example

Imagine I have a vector (the contents of which are not relevant for this example)

aux<-c(1:5)

I need to create a data frame that has the same vector repeating itself n times (n can vary, sometimes it is 8 times, sometimes it is 7)

I did it like this for repeating itself 8 times:

aux.df<-data.frame(aux,aux,aux,aux,aux,aux,aux,aux)

This got me the result I wanted but you can see why it's not an ideal way...

is there a package, function, way to tell R to repeat the vector 'aux' 8 times?

I also tried creating a matrix and then transforming it into a data frame but that didn't work and I got a weird data frame with vectors inside of each cell... what I tried that didn't work:

aux.df<- as.data.frame(matrix(aux, nrows=5, ncol=8))

Solution

  • Using replicate().

    as.data.frame(replicate(8, aux))
    #   V1 V2 V3 V4 V5 V6 V7 V8
    # 1  1  1  1  1  1  1  1  1
    # 2  2  2  2  2  2  2  2  2
    # 3  3  3  3  3  3  3  3  3
    # 4  4  4  4  4  4  4  4  4
    # 5  5  5  5  5  5  5  5  5