In my dataframe there are multiple rows for a single observation (each referenced by ref). I would like to collapse the rows and create new columns for the keyword and the reg_birth columns.
df1 <- structure(list(rif = c("text10", "text10", "text10", "text11", "text11"),
date = c("20180329", "20180329", "20180329", "20180329", "20180329"),
keyword = c("Lucca", "Piacenza", "Milano", "Cascina", "Padova"),
reg_birth = c("Tuscany", "Emilia", "Lombardy", "Veneto", "Veneto")),
row.names = c(NA, 5L), class = "data.frame")
If I just want to create the columns for the 'keyword' column I used this code, as shown in this answer.
df1 %>% group_by(rif,date) %>%
mutate(n = row_number()) %>%
pivot_wider(id_cols = c(rif,date), values_from = keyword, names_from = n, names_prefix = 'keyword')
However, I don't know how to do the same for an additional column (reg_birth in this case).
This is my expected output
rif keyword reg.birth keyword2 reg_birth2 keyword3 reg_birth3
1 text10 Lucca Tuscany Piacenza Emilia Milano Lombardy
2 text11 Cascina Veneto Padova Veneto <NA> <NA>
Thank you.