Reputation: 3
first time posting so if something is wrong please let me know, I have a dataframe in R that is divided in the following way:
location | type | amount | produt |
---|---|---|---|
a | x | 10 | p1 |
a | x | 20 | p2 |
b | x | 50 | p5 |
b | y | 100 | p10 |
In the end I need to group the locations into a single line and make the "type" column to become new columns with the value of the "product" and "amount" column, just like this :
location | A_P_X | A_P_Y |
---|---|---|
a | p1_10,p2_20 | |
b | p5_50 | p10_100 |
I tried to make the new coluns using one hot encoding but I run into problem when tring to fill the new columns based on their original "type" value
Upvotes: 0
Views: 37
Reputation: 66415
library(tidyverse)
df %>%
unite("val", produt:amount, sep = "_") %>%
mutate(type = paste0("A_P_", toupper(type))) %>%
pivot_wider(names_from = type, values_from = val,
values_fn = list(val = ~paste(., collapse = ", ")))
result
# A tibble: 2 x 3
location A_P_X A_P_Y
<chr> <chr> <chr>
1 a p1_10, p2_20 NA
2 b p5_50 p10_100
Upvotes: 1