【问题标题】:How to count number of values by condition in dataframe?如何按数据框中的条件计算值的数量?
【发布时间】:2022-08-09 21:15:30
【问题描述】:

从这个数据框中,我需要按列计算 TRUE 和 FALSE 值的数量。但是,由于我需要使流程自动化,我不能用列名或列索引来计算它们。我需要别的东西

df1  <- c(TRUE,TRUE,FALSE,TRUE,TRUE)
df2 <- c(TRUE,FALSE,FALSE,TRUE,TRUE)
df3 <- c(FALSE,TRUE,TRUE,TRUE,TRUE)

df <- data.frame(df1,df2,df3)

预期结果:

      df1    df2    df3
 TRUE   4      3      4
FALSE   1      2      1
  • sapply(df, sum)

标签: r loops for-loop dplyr lapply


【解决方案1】:

使用colSums

nbTRUE <- colSums(df)
nbFALSE <- nrow(df) - nbTRUE

【讨论】:

    猜你喜欢
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多