NA and double in one column

i have got a data frame in which one column looks like this:

# A tibble: 50,853 x 1
   mycol
   <dbl>
 1     0
 2     0
 3     0
 4     0
 5     0
 6     0
 7     89
 8     90
 9     0
10     123
# … with 50,843 more rows

i want to convert all observations with 0 into NAs.
However when I try this with df %>% mutate(mycol=if_else(mycol==0, NA, mycol))
I get the error `false` must be a logical vector, not a double vector.
Is there any other solution?
Thank You very much

You can use ifelse() instead of if_else() which has stricter type checks.

Another option is na_if():

If you want to stick with if_else(), you need to specify the appropriate NA constant to be used (the default NA is of type logical). Since the vector you are operating on is of type double, you would use NA_real_.

library(dplyr, warn.conflicts = FALSE)

df <- tibble(mycol = c(0, 0, 0, 0, 0, 89, 90, 0, 123))

df %>% mutate(mycol = if_else(mycol == 0, NA_real_, mycol))
#> # A tibble: 9 x 1
#>   mycol
#>   <dbl>
#> 1    NA
#> 2    NA
#> 3    NA
#> 4    NA
#> 5    NA
#> 6    89
#> 7    90
#> 8    NA
#> 9   123

Created on 2020-05-07 by the reprex package (v0.3.0)

1 Like

just like to explain how you will handle number with char or vice versa ..

library(dplyr)

df <- tibble(mycol = c(0, 0, 0, 0, 0, 89, 90, 0, 123))
str(df)
df$mycol <- as.character(df$mycol)
str(df)
df %>% mutate(mycol=if_else(mycol== 0, "NA", mycol))
str(df)
df$mycol <- as.numeric(df$mycol)
str(df)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.