[英]How to count instances of something in one column given value of another column?
I basically have a data frame like this: 我基本上有一个像这样的数据框:
Name Value
a TRUE
a TRUE
b FALSE
a FALSE
c TRUE
but longer and I want to get the amount of times a, b, and, c appear. 但更长,我想获得a,b和c出现的次数。 I also want to get the amount of time TRUE appears for a, b, and c. 我也想获取a,b和c出现TRUE的时间。
So basically, I want: 所以基本上,我想要:
Name Count TRUEs
a 3 2
b 1 0
c 1 1
How would I do that? 我该怎么做?
With dplyr
: 与dplyr
:
library(dplyr)
df %>% group_by(Name) %>% summarise(Count = n(), Trues = sum(Value == TRUE))
# A tibble: 3 x 3
Name Count Trues
<chr> <int> <int>
1 a 3 2
2 b 1 0
3 c 1 1
A base R alternative using by
使用A基础R替代by
do.call(rbind, by(df, df$Name, FUN = function(x)
c(Count = length(x$Value), TRUEs = sum(x$Value == TRUE))))
# Count TRUEs
#a 3 2
#b 1 0
#c 1 1
Or using tapply
或使用tapply
do.call(rbind, with(df, tapply(Value, Name, FUN = function(x)
c(Count = length(x), TRUEs = sum(x == TRUE)))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.