nouse
nouse

Reputation: 3461

Remove columns from a dataframe meeting a treshold of non-zero values

I want to split a dataframe by the number of non-zero values, say I want to remove all columns with more than n zeros. I know how to remove all zero-sum columns:

df[, colSums(df) != 0]

But how to do this for any treshold for zero elements ?

Upvotes: 1

Views: 68

Answers (1)

akrun
akrun

Reputation: 886978

We need to create a logical matrix and then do the colSums

 n <- 3
 df[colSums(df==0) <= n]

data

 set.seed(22)
 df <- as.data.frame(matrix( sample(0:4, 5*20, replace=TRUE), ncol=5))

Upvotes: 2

Related Questions