I use Any and All functions quite a bit in R but I would like some flexibility. Is there any function that give tell me if a certain percent of the values are true or false?
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
Desired output
pseudo code
60% of df == 5
TRUE
90% of df == 5
FALSE
We can use the mean
of logical vector and check if that value is equal to a particular percentage
mean(df$x== 5) >= 0.6
#[1] TRUE
Or in a pipe (%>%
)
library(magrittr)
library(dplyr)
df %>%
pull(x) %>%
equals(5) %>%
mean %>%
is_weakly_greater_than(0.6)
#[1] TRUE
Or create a frequency table of logical vector
and get the proportion with 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"))