1

Given such a data frame:

V1     V2
x      3
y      2
z      4
...

I'd like to transform it to:

V1
x
x
x
y
y
z
z
z
z

Each element in V1 has repeated for n times and n is the corresponding value in V2. Do you know how to implement it quickly without for loop? Thanks in advance!

Jaap
  • 81,064
  • 34
  • 182
  • 193

2 Answers2

4

Simple, where x is your data.frame:

data.frame(V1 = rep(x$V1, x$V2))
Thomas
  • 43,637
  • 12
  • 109
  • 140
1

We could use expandRows

library(splitstackshape)
expandRows(df1, "V2")
#    V1
#1    x
#1.1  x
#1.2  x
#2    y
#2.1  y
#3    z
#3.1  z
#3.2  z
#3.3  z
akrun
  • 874,273
  • 37
  • 540
  • 662