2

I would like to repeat elements in one column according to the values in another column. For example

col1 <- c("A","B","A","C","B")
col2 <- c(2,3,1,3,4)
data <- data.frame(col1,col2)

To give

col1<-c("A","A","B","B","B","A","C","C","C","B","B","B","B")
col2<-c(2,2,3,3,3,1,3,3,3,4,4,4,4)
data <- data.frame(col1,col2)

I tried the rep() command, but it only repeats col1 based on the first row of col2 ("In rep(c(col1), each = col2) : first element used of 'each' argument")

dat_new<-data.frame(rep(c(col1),each=col2))

Thanks

Choco Late
  • 31
  • 1
  • 2

1 Answers1

1

We can replicate by the sequence of rows to expand the dataset.

 data[rep(1:nrow(data), data$col2),]
akrun
  • 874,273
  • 37
  • 540
  • 662