0

My data is

ID n
1  3
2  2
3  4

I want it to be like

ID
1
1
1
2
2
3
3
3
3

The only way I can solve it is that I use for loop.

Below is my code

y <- read.csv('Desktop/勞研所/20220831 攜出/py.csv')

data <- data.frame()

for (i in 1:14909545){
  
  id <- y[i, 1]
  count <- y[i, 2]
  
  df <- data.frame(ID = rep(id, count))
  
  data <- rbind(data, df) 
}

As u can see, the number of whole data is 14909545! That is, I have to run 14909545 times, which takes me a lot of time.

Maël
  • 45,206
  • 3
  • 29
  • 67
Yu-Chi Syu
  • 25
  • 4

2 Answers2

2

Use tidyr::uncount:

library(tidyr)
uncount(df, n)
  ID
1  1
2  1
3  1
4  2
5  2
6  3
7  3
8  3
9  3
Maël
  • 45,206
  • 3
  • 29
  • 67
2

You can try the following base R option with rep

res <- with(df, data.frame(ID = rep(ID,n)))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81