Reputation: 2297
I have a df that looks like this:
it can be build using codes:
df<- structure(list(Gender = c("F", "F", "M", "M", "F", "F"), Subject = c("M",
"E", "E", "M", "M", "E")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
Now I want to build a summary table for it. What is the best method to build one like this:
So far I have done:
tb1<-df %>% group_by(Gender, Subject)%>%
summarise(total=n())
tb1w =tb1 %>%
spread(Subject, total)
Is there a better way to do it? just feel too many steps in order to get such simple table. Any suggestion on this? If I have to go this way, is it a better way to do it so I can get the table I want? such as better col names?
Many thanks.
Upvotes: 1
Views: 40
Reputation: 101343
A base R option using aggregate
> aggregate(. ~ Gender, df, table)
Gender Subject.E Subject.M
1 F 2 2
2 M 1 1
A data.table
option using dcast
dcast(setDT(df), Gender ~ Subject)
which gives
Gender E M
1: F 2 2
2: M 1 1
Upvotes: 1