s666
s666

Reputation: 274

function argument in filter of dplyr in R

filter(data, function(x) sum(is.na(x))>2)

I want to use this piece of code to get a subset of data which contains rows involve less than 2 NA values, however, the error occurs:

Error: Argument 2 filter condition does not evaluate to a logical vector

Just wondering the reason and how could I deal with it? Many thanks!

Upvotes: 1

Views: 131

Answers (1)

akrun
akrun

Reputation: 886938

We can use filter with rowSums

library(dplyr)
data %>%
   filter(rowSums(is.na(.)) < 2)

Or using base R

data[rowSums(is.na(data)) < 2,]

data

data <- data.frame(col1 = c(2, 3, NA), col2 = c(2, NA, NA), col3 = c(1, 2, 3))

Upvotes: 1

Related Questions