Produce duplicate rows based on the value in a column

Hi there,

I have a data frame that has a "value" column, which is the value of an observation for each "group". I also have a "count" column, which is the number of time that value appears for each group. For example:

  ~group, ~count, ~value,
     "A",      2,     10,
     "B",      1,     12,
     "B",      2,     13

What I am trying to do is create a dataframe that duplicates the rows for each group / value combination, based on the count column. Kind of an "un-summarize". So the dataframe above would end up like this:


Seems relatively straightforward but I can't figure it out! Any help would be appreciated. (In case this seems like a strange task, the reason I am doing it is for visualization purposes).

Thank you!


You can use the uncout() function from the tidyr package.

DF <- tibble::tribble(
   ~group, ~count, ~value,
   "A",      2,     10,
   "B",      1,     12,
   "B",      2,     13
DF |> uncount(count)
# A tibble: 5 x 2
  group value
  <chr> <dbl>
1 A        10
2 A        10
3 B        12
4 B        13
5 B        13

Brilliant, thank you!

This topic was automatically closed 7 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.