blue-sky
blue-sky

Reputation: 53876

Filter remove NA string or value from tibble

Here I'm attempting to remove NA values from a tibble :

mc = as_tibble(c("NA" , NA , "ls", "test"))
mc <- filter(mc , is.na == TRUE)

But error is returned :

> mc = as_tibble(c("NA" , NA , "ls", "test"))
> mc <- filter(mc , is.na == TRUE)
Error in filter_impl(.data, quo) : 
Evaluation error: comparison (1) is possible only for atomic and list types.

How to remove NA values from this tibble ?

Upvotes: 1

Views: 8059

Answers (3)

Agile Bean
Agile Bean

Reputation: 7161

The solutions given by @tyluRp and @danh work perfectly fine.

Just wanted to add another alternative solution with the advantages

  • simpler code
  • shorter - for the lazy ones like me :)

See this one-liner:

mc %>% replace(. == "NA", NA) %>% na.omit

Upvotes: 0

danh
danh

Reputation: 638

If you simply want to remove actual NA values:

library(dplyr)
filter(mc, !is.na(value))

Alternatively (this will check all columns, not just the specified column as above):

na.omit(mc)

If you want to remove both NA values, and values equaling the string "NA":

library(dplyr)
filter(mc, !is.na(value), !value == "NA")

Upvotes: 1

tyluRp
tyluRp

Reputation: 4768

Try:

library(tidyverse)

mc %>% 
  mutate(value = replace(value, value == "NA", NA)) %>% 
  drop_na()

Which gives:

# A tibble: 2 x 1
  value
  <chr>
1    ls
2  test

Second line replaces all "NA" to a real <NA>. Then the third line drops all <NA> values.

Upvotes: 2

Related Questions