简体   繁体   English

在给定另一列的值的情况下,如何计算某列中某物的实例?

[英]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.

相关问题 如何根据另一列中的模式条件计算数据框的一列中的实例数? - How can I count the number of instances within one column of a dataframe based on the condition of a pattern within another column? 如果 R 满足另一列中的条件,如何让 R 计算列中的值? - How to get R to count a value in a column if it meets a criteria in another column? 给定另外两个列的名称,计算一列中的唯一实例 - Count unique instances in a column given the names of two other columns 如何计算一行的列值大于另一行的分组对的数量? - How can I count the number of grouped pairs in which one row's column value is greater than another? 如果我在另一列中有特定值,如何替换列中的 NA 值? - How can I replace an NA value in a column for something if I have an specific value in another column? 一列中的值取决于另一列中的值 - The value in one column depends in the value of another column R:如何根据此搜索读取列、查找值并计算另一列中的某些内容? - R: How to read a column, find a value and calculate something in another column based in this search? 如果与该行对应的另一列中的值首次在两年内动态出现,则计算一列中的值的数量 - count number of values in one column if the value in another column corresponding to this row is first occurrence dynamically within two years 如何根据同一列中另一个值的出现来计算变量? - How to count the variables depending on the appearance of another value in the same column? 如何计算所有行中列中某个值的实例数? - How do I count the number of instances of a value in a column across all rows?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM