team17
team17

Reputation: 816

Insert n values in dataframe where n is described in other list

I have a dataframe a and a list b:

  a = data.frame(a = c(1:4), c = c(1:4), b = c(1:4) )
  b = c(4,3,4,5)
  names(b) = c("a","c","b", "d")

> a
  a c b
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4

>b
a c b d 
4 3 4 5 

I want to insert in a n copies of each column where n is described by b[i]. In this example a should look like:

   a c b
1  1 1 1
2  1 1 1
3  1 1 1
4  1 1 1
5  2 2 2
6  2 2 2
7  2 2 2
8  3 3 3
9  3 3 3
10 3 3 3
11 3 3 3
12 4 4 4
13 4 4 4
14 4 4 4
15 4 4 4
16 4 4 4

I think this should be easy in R, but after much of experimentig with mapply function i could not get the wanted result.

Upvotes: 1

Views: 46

Answers (2)

Sotos
Sotos

Reputation: 51592

Package splitstackshape has a very useful function for expanding the rows of a data frame,

library(splitstackshape)
expandRows(a, b, count.is.col = FALSE)

Upvotes: 2

zx8754
zx8754

Reputation: 56179

Try this:

a[rep(seq_along(b), b), ]

Upvotes: 2

Related Questions