Remove Columns from a table that are 90% one value

Viewed 28

Example Data:

A<- c(1,2,3,4,1,2,3,4,1,2)
B<- c(A,B,C,D,E,F,G,H,I,J)
C<- c(1,1,1,1,1,1,1,1,1,0)
D<- c(TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,FALSE)
df1<-data.frame(A,B,C,D)

df1 %>%
  select_if(
    ###column is <90% one value
  )

So I have a table that has a few columns that are predominantly one value--like C and D in the above example. I need to get rid of any columns that are 90% or more one unique value. How can I get rid of the columns that fit this criteria?

1 Answers

We may use select with where, get the frequency count with table, convert to proportions, get the max value and check if it is less than .90 to select the particular column

library(dplyr)
df1 <- df1 %>% 
    select(where(~ max(proportions(table(.))) < .90))

data

df1 <- structure(list(A = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2), B = c("A", 
"B", "C", "D", "E", "F", "G", "H", "I", "J"), C = c(1, 1, 1, 
1, 1, 1, 1, 1, 1, 0), D = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 
TRUE, TRUE, TRUE, FALSE)), class = "data.frame", row.names = c(NA, 
-10L))
Related