I just posted a question recently asking how to reshape data from a long table to a wide table. Then I found spread()
is a quite handy function for doing this. So now I need some further development on my previous post.
Let's suppose we have a table like this:
id1 | id2 | info | action_time | action_comment |
1 | a | info1 | time1 | comment1 |
1 | a | info1 | time2 | comment2 |
1 | a | info1 | time3 | comment3 |
2 | b | info2 | time4 | comment4 |
2 | b | info2 | time5 | comment5 |
And I would like to change it to something like this:
id1 | id2 | info |action_time 1|action_comment1 |action_time 2|action_comment2 |action_time 3|action_comment3 |
1 | a | info1 | time1 | comment1 | time2 | comment2 | time3 | comment3 |
2 | b | info2 | time4 | comment4 | time5 | comment5 | | |
So the difference between this question and my previous question is I added another column and I need it to be reshaped as well.
I'm thinking to use
library(dplyr)
library(tidyr)
df %>%
group_by(id1) %>%
mutate(action_no = paste("action_time", row_number())) %>%
spread(action_no, value = c(action_time, action_comment))
But it gives me an error message when I put two values in value
argument saying : Invalid column specification.
I really like the idea of using such %>%
operator to manipulate data, so I'm keen to know how to correct my code to make this happen.
Much appreciate for the help