1

I am trying to add multiple rows to each entry in a dataframe in R.

for instance:

c <- c("a", "b", "c")

d <- c(1, 2, 3, 4)

For "a" i want to add rows with 1, 2, 3, and 4. etc.

cbind(c[1], d)

     [,1] [,2]
[1,] a  1 
[2,] a  2 
[3,] a  3 
[4,] a  4 

I have a solution that works, but it takes too long.

tmp2<- data.frame() 
for (i in 1:length(c)) {
  tmp1 <- cbind(c[i], d)
  tmp2 <- rbind(tmp2, tmp1)
}

end result:

> tmp2
   V1 d
1   a 1
2   a 2
3   a 3
4   a 4
5   b 1
6   b 2
7   b 3
8   b 4
9   c 1
10  c 2
11  c 3
12  c 4

Any better way to do this?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213

0 Answers0