Expand Rows But Keep All Columns


This should be rather simple, I would like to expand rows of my data set. The criteria to expand the rows is equal to a value in a specified column. In my code below that column is row_nbr2. Currently I can expand my rows the way I want however, the functions deletes all but two columns. I have two different ways of expanding my data set:



I am grouping by id, creating a new column called 'md' and expanding the rows equal to the value in the row_nbr2 column.

Any thoughts?


df <- tibble(x = c("a", "b"), n = c(1, 2))
uncount(df, n)
1 Like

Thank you very much that was simple enough. Quick question though, in addition to wanting the rows expanded, I also want the function to create a new column that would number the rows. For example, if id A's rows expanded to 3 rows then I would want a column to include 1,2,3. Can I incorporate something like that with uncount?

I expanded the pipeline for that:

df <- tibble(x = c("a", "b","c"), n = c(1, 2,4)) %>%
uncount( n) %>% group_by(x) %>% mutate(rn=row_number())
1 Like

Use the .id argument. Reading documentation is a great way to learn new things.

1 Like

@Yarnabrina solution is much nicer, thank you.

df <- tibble(x = c("a", "b","c"), n = c(1, 2,4)) %>%
uncount( n, id="rn")

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