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
  • 77,147
  • 31
  • 174
  • 185

2 Answers2

4

Simple, where x is your data.frame:

data.frame(V1 = rep(x$V1, x$V2))
Thomas
  • 42,067
  • 12
  • 102
  • 136
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
  • 789,025
  • 32
  • 460
  • 575