Reputation: 2307
I have a df that looks like this:
It can be build using codes:
structure(list(ID = c(1, 2, 3, 4, 5), Pass = c(0, 1, 1, 1, 1),
Math = c(0, 0, 1, 1, 1), ELA = c(0, 1, 0, 1, 0), PE = c(0,
0, 1, 1, 1)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))
How can I get a summary table like this;
I thought I could do it by:
st_count <- Reduce(function(x,y) merge(x, y, all = TRUE),list(table(df$Math),
table(df$ELA),
table(df$PE)))
But it did not work as i want. I think i might complicate a simple question. any suggestion?
Upvotes: 0
Views: 50
Reputation: 39737
You can use colSums
:
colSums(df[3:5])
#Math ELA PE
# 3 2 3
and to come to columns ether cbind
cbind(colSums(df[3:5]))
# [,1]
#Math 3
#ELA 2
#PE 3
or stack
stack(colSums(df[3:5]))[2:1]
# ind values
#1 Math 3
#2 ELA 2
#3 PE 3
Alternatively you can use aggregate
aggregate(values~ind, stack(df[3:5]), sum)
# ind values
#1 Math 3
#2 ELA 2
#3 PE 3
or xtabs
xtabs(values~ind, stack(df[3:5]))
#ind
#Math ELA PE
# 3 2 3
or sapply
sapply(df[3:5], sum)
#Math ELA PE
# 3 2 3
or apply
apply(df[3:5], 2, sum)
#Math ELA PE
# 3 2 3
...
The names can be set by using setNames
or names
you have created an object.
Upvotes: 1
Reputation: 887971
Using tidyverse
library(dplyr)
library(tidyr)
df1 %>%
pivot_longer(cols = -ID) %>%
group_by(Subject = name) %>%
summarise(Count = sum(value))
Upvotes: 1
Reputation: 102910
Try stack
+ colSums
> setNames(rev(stack(colSums(df))),c("Subject","Student Count"))
Subject Student Count
1 Math 4
2 ELA 2
3 PE 3
Upvotes: 1