Need help to reshape my data

Hi!

I have data looking like this:

ID Category Value
1 S 3
1 M 2
2 S 1
2 M 4

I want to remove the value column and rather have one row for each value like this:

ID Category Value
1 S
1 S
1 S
1 M
1 M
2 S
2 M
2 M
2 M
2 M

Do anyone have any ideas on how to do this?

Would be very greatful for all help. Thank you!

Regards M

Welcome to the community!

You can use tidyr::uncount. Here's a link to a related SO thread.

library(readr)
library(tidyr)

sample_data <- read_delim(file = "ID Category Value
1 S 3
1 M 2
2 S 1
2 M 4",
                          delim = " ",
                          col_names = TRUE)

sample_data %>%
    uncount(weights = Value)
#> # A tibble: 10 x 2
#>       ID Category
#>    <dbl> <chr>   
#>  1     1 S       
#>  2     1 S       
#>  3     1 S       
#>  4     1 M       
#>  5     1 M       
#>  6     2 S       
#>  7     2 M       
#>  8     2 M       
#>  9     2 M       
#> 10     2 M

Hope this helps.

1 Like

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

Thanks a lot, that worked fine!