I have a dataframe with two columns: id and category.
id <- c(1,1,1,2,2,2,3,3,4,5,5,6)
categoria <- c("A","B","C","B","A","C","A","C","A","B","C","B")
df <- data.frame(id,categoria)
Sometimes an id appears in more than one row, associated with different categories. Is there a way to move the rows corresponding to the same id as new columns, so that the information for each id remains in the same row? The desired result would be:
You can use take it from long to wide, for this you can use the package
tidyr
, but you need the counter of each category.The code would be:
In your case, the id is sorted, but if it wasn't, you could use an arrange(
df %>% arrange(id)
), because you have to create a counter per category.The result obtained.