Multiply rows based on a column values

Hi there! I want to multiply the rows in a dataframe based on another column that indicates the number of times that the observation has happened. Here are the columns i have initially in my dataframe:

a <- c(5, 4, 3, 2, 1)
b <- c(1, 2, 3, 4, 5)
freq <- (1, 2, 2, 1, 3)

I want to get my dataframe like this:

a <- c(5, 4, 4, 3, 3, 2, 1, 1, 1)
b<- c(1, 2, 2, 3, 3, 4, 5, 5, 5)
`` `

Thanks!

Hi, you can use the uncount function from tidyr:

df <- data.frame(a = 5:1, b = 1:5)
freq <- c(1, 2, 2, 1, 3)
df %>%
     mutate(freq = freq) %>%
     uncount(freq)

It worked!

Thank you!!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.