Shahzad
Shahzad

Reputation: 2049

Filtering out columns in R

Referring to another post# Filtering out multiple columns in R ; there it was asked to filter out columns with all 0's (All the values in the column are 0). Using the following code:

f0 <- function(x) any(x!=0) & is.numeric(x)
trainingdata <- lapply(trainingdata, function(data) cbind(label=data$label, 
                                colwise(identity, f0)(data)))

one can filter out columns containing 0's only. There is also a need to filter out columns containing 1's only (I mean all the values in the column are 1). I tried the following:

f0 <- function(x) all(x==1) | any(x!=0) & is.numeric(x)

OR

f0 <- function(x) all(x!=1) | any(x!=0) & is.numeric(x)

but its not working.

Upvotes: 0

Views: 972

Answers (1)

Justin
Justin

Reputation: 43255

Your second function with a logicalAND rather than OR and the check any(x!=1) should work.

However, I would write these as two separate functions and do each check independently for clarity.

Upvotes: 2

Related Questions