'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 1:[1]
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
Solution 2:[2]
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))
Solution 3:[3]
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))
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jay.sf |
| Solution 2 | PatrickL |
| Solution 3 | |
| Solution 4 | ThomasIsCoding |
