【问题标题】:How to check if some values are true [duplicate]如何检查某些值是否为真[重复]
【发布时间】:2019-07-10 06:36:58
【问题描述】:

我在 R 中经常使用 Any 和 All 函数,但我想要一些灵活性。是否有任何函数可以告诉我某个百分比的值是真还是假?

df
    x
1   5
2   5
3   5
4   4
5   3
6   5
7   5
8   5
9   5
10  5

all(df$x==5)
[1] FALSE

any(df$x==5)
[1] TRUE

期望的输出

伪代码

60% of df == 5
TRUE
90% of df == 5
FALSE 

【问题讨论】:

    标签: r any


    【解决方案1】:

    你可以的,

    (sum(x == 5) / length(x)) >= 0.6
    #[1] TRUE
    
    (sum(x == 5) / length(x)) >= 0.9
    #[1] FALSE
    

    注意:您需要为要检查的百分比指定 >= 而不是 ==,以适应 df == 5 的 60% 的条件 em>

    【讨论】:

      【解决方案2】:

      我们可以使用逻辑向量的mean 并检查该值是否等于特定百分比

      mean(df$x== 5) >= 0.6
      #[1] TRUE
      

      或在管道中 (%>%)

      library(magrittr)
      library(dplyr)
      df %>%
         pull(x) %>%
         equals(5) %>%
         mean %>% 
         is_weakly_greater_than(0.6)
      #[1] TRUE
      

      或者创建逻辑vector的频率表,得到与prop.table的比例

      prop.table(table(df$x== 5))
      #   FALSE  TRUE 
      #   0.2   0.8 
      

      数据

      df <- structure(list(x = c(5L, 5L, 5L, 4L, 3L, 5L, 5L, 5L, 5L, 5L)),
      class = "data.frame", row.names = c("1", 
      "2", "3", "4", "5", "6", "7", "8", "9", "10"))
      

      【讨论】:

        【解决方案3】:

        在相当全面的答案上没有太多补充,但这是一个有趣的问题。

        数据

        set.seed(123)
        dta <- data.frame(colA = sample(x = 1:10, size = 20, replace = TRUE))
        

        Vectorize

        prop.table(table(Vectorize(isTRUE)(dta$colA == 5)))
        # FALSE  TRUE 
        # 0.85  0.15 
        

        更具体地说是您的问题:

        是否有任何功能可以告诉我是否有一定百分比的 值是真还是假?

        res_perc[["TRUE"]] == 0.15
        # TRUE
        

        rapportools::percent

        使用rapportools 包中提供的简单percent 函数。

        rapportools::percent(dta$colA == 5)
        # [1] 15
        

        dplyr

        结果不错。

        library(tidyverse)
        dta %>% 
            count(colA == 5) %>% 
            mutate(n_pct = n / sum(n))
        # A tibble: 2 x 3
        # `colA == 5`     n    n_pct
        # <lgl>       <int>    <dbl>
        # 1 FALSE        17    0.85
        # 2 TRUE          3    0.15
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-11
          相关资源
          最近更新 更多