Home > Software engineering >  Is there an easy way to create a data frame in R with the same vector repeating itself "n"
Is there an easy way to create a data frame in R with the same vector repeating itself "n"

Time:01-27

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))

CodePudding user response:

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

CodePudding user response:

parameters

aux<-c(1:5)

n<-8

vector aux repeated as columns

aux.df<-as.data.frame(matrix(rep(aux,n),ncol=n,byrow = F))

vector aux repeated as rows

aux.df<-as.data.frame(matrix(rep(aux,n),nrow=n,byrow = T))

CodePudding user response:

I'd suggest this (which does not require to specific the length of the vector):

do.call(cbind.data.frame, rep(list(aux), 8)))

But, from your example, you could do:

as.data.frame(matrix(aux, nrow=5, ncol=8))
  •  Tags:  
  • Related