I have a 3 columns data frame, which I try to convert it to a matrix.
Name Act value
Alex C1 100
John C2 100
Matt C3 252
Alex C1 456
Alex C5 234
John C5 456
Tina C2 897
Matt C2 652
Jorge C1 344
Alex C1 34
Matt C3 231
I want to have something like:
C1 C1.1 C1.2 C2 C3 C3.1 C4 C5
Alex 100 456 34 234
John 100 456
Matt 652 252 231
Tina 897
Jorge 344
I mean, since I have similar names that made the same act having different/same score, I want to instead of summing the values and put them in a cell of a matrix, generate a separate column for that act (while having a number at the end of the name). Thanks
With tidyverse
, you can do:
df %>%
group_by(Name) %>%
mutate(Act = make.unique(Act)) %>%
spread(Act, value)
Name C1 C1.1 C1.2 C2 C3 C3.1 C5
<chr> <int> <int> <int> <int> <int> <int> <int>
1 Alex 100 456 34 NA NA NA 234
2 John NA NA NA 100 NA NA 456
3 Jorge 344 NA NA NA NA NA NA
4 Matt NA NA NA 652 252 231 NA
5 Tina NA NA NA 897 NA NA NA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.