1

I was using the following code to get rid of empty cell in my dataframe.

df %>%
 # recode empty strings "" by NAs
 na_if("") %>%
 # remove NAs
 na.omit`

it was working fine till recently but now i am getting the following error

Error in na_if(): ! Can't convert y to match type of x <tbl_df>. Run rlang::last_error() to see where the error occurred.

rlang::last_error() <error/vctrs_error_cast> Error in na_if(): ! Can't convert y to match type of x <tbl_df>.

I am using r version 4.1.3 and dplyr package 1.1.0

Note: i am getting the same error when using

df %>% mutate_all(~na_if(.,"")) %>%
  na.om`it
  • 3
    What is `class(df)`? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. I can't find any references to `na_if` working on an entire data.frame. The documentation sounds like the first parameter needs to be a vector. Are you sure your first code block used to work correctly? Were you using packages other than `dplyr`? – MrFlick Feb 10 '23 at 17:47
  • 1
    Adding to what @MrFlick said, `na_if` is intended to replace a value of one type with a different value of that same type. You're trying to replace (part or all of) a data frame with a string. – camille Feb 10 '23 at 17:58
  • FWIW `na_if()` used to _accidentally_ allow you to replace elements of an entire data frame, but we considered this off label usage and removed it in dplyr 1.1.0. It was never intended to work that way. As others have noted, both `x` and `y` should be vectors of the same type. You can see a news bullet for this in the `na_if()` section here https://dplyr.tidyverse.org/news/index.html#vctrs-1-1-0 – Davis Vaughan Feb 10 '23 at 20:27
  • @DavisVaughan good for you for removing what you considered off-label use of something you are building. but may I humbly ask what is the proper way to do such a thing in the entire dataframe? Our team has been using it extensively and we don't have an alternative yet – gota Jul 14 '23 at 13:53

1 Answers1

0
library(tidyverse)
set.seed(2023)
df <- data.frame(values=sample(c(letters[1:3],""),30,T))

no_na_df <- df %>%
  na_if("") %>%
  na.omit()
map_dbl(list(df,no_na_df),nrow) # print number of rows of wach data set

Output:
[1] 30 22

If i may suggest an easier base R version (can be used in the context of mtate as well:

replace(df$values,which(df$values==""),NA)

df %>% mutate(values_no_na=replace(values,which(values==""),NA)) %>% view()

enter image description here

RYann
  • 567
  • 1
  • 7