Reputation: 410
I'm new in R; trying to do some basic data manipulations. However, I've been stuck with this problem for 2 days.
Suppose I have a data frame like the below and it contains 60 obs which every variable in the "category" column has the same amount:
category cond
1 A 1
2 B 2
3 C 1
4 D 1
5 E 1
6 F 3
7 A 5
8 B 0
.. .. ..
60 F 2
Desired new data frame (by the "cond" column):
A B C D E F
1 1 2 1 1 0 3
2 5 0 . . . .
3 . . . . . .
. . . . . . .
. . . . . . .
10 . . . . . 2
Since the first data frame has a 60 row(all variables in the "category" column has equal number 60/6=10) new data frame has 10 rows.
I've tried this for example
A<-old%>% filter(category =="A")%>%summarise(`cond`)
B<-old%>% filter(category =="B")%>%summarise(`cond`)
new<-cbind(A,B)
... .. This works for me but it's taking a lot of time and changing column names another part of this problem.
Thanks in advance.
Upvotes: 0
Views: 1165
Reputation: 537
Is there a typo in your expected result?
At a untested guess:
require(dplyr)
old %>%
spread(A,B) -> new
Upvotes: 0
Reputation: 26218
Try this
df %>% group_by(category) %>% mutate(id = row_number()) %>% ungroup() %>% pivot_wider(id_cols = id, names_from = category, values_from = cond) %>% select(-id)
Upvotes: 1