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

976 views Asked by At

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

There are 3 answers

0
jay.sf On BEST ANSWER

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
0
PatrickL On

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

0
ThomasIsCoding On

Here are some possible opitons

> data.frame(aux = aux)[rep(1, 8)]
  aux aux.1 aux.2 aux.3 aux.4 aux.5 aux.6 aux.7
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

> data.frame(kronecker(t(rep(1, 8)), aux))
  X1 X2 X3 X4 X5 X6 X7 X8
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

> data.frame(outer(aux, rep(1, 8)))
  X1 X2 X3 X4 X5 X6 X7 X8
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

> list2DF(rep(list(aux), 8))

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