Stataq
Stataq

Reputation: 2297

how to build a summary table without reshape

I have a df that looks like this:

enter image description here

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:

enter image description here

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

Answers (2)

ThomasIsCoding
ThomasIsCoding

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

user12256545
user12256545

Reputation: 3002

R has the table function for this application:

table(df)

Upvotes: 3

Related Questions