Reputation: 181
I am trying to count the number of cells greater than 0 by group, and I need help as to how to approach this.
My data looks like this:
Group Number of Shoes
1 0
1 1
1 2
2 0
2 NA
2 1
3 1
3 2
3 2
And I want this:
Group Shoe owners
1 2
2 1
3 3
Upvotes: 2
Views: 4976
Reputation: 887571
we can also use data.table
library(data.table)
setDT(df1)[Number.of.Shoes >0, .(Shoe.Owners = .N), Group]
# Group Shoe.Owners
#1: 1 2
#2: 2 1
#3: 3 3
Upvotes: 2
Reputation: 4187
You can do this simply with:
aggregate(Number.of.Shoes ~ Group, df, function(x) sum(x > 0, na.rm = TRUE))
The result:
Group Number.of.Shoes
1 1 2
2 2 1
3 3 3
This can also be done with dplyr
package:
library(dplyr)
df %>%
group_by(Group) %>%
summarise(counts = sum(Number.of.Shoes > 0, na.rm = TRUE))
Upvotes: 5