如何检查某些值是否为真

时间:2019-07-10 06:36:58

标签: r any

我在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 

3 个答案:

答案 0 :(得分:5)

可以,

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

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

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

答案 1 :(得分:4)

我们可以使用逻辑向量的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"))

答案 2 :(得分: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

使用percent软件包中提供的简单rapportools功能。

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
相关问题