0

I have a dataframe column populated with strings and NAs, like this:

df <- data.frame(col=as.character(c(NA,'', 'text', '', NA,'text')))

In this case, ' ' and NA both represent NA, and I am trying to standardize so both are NA or so both are ' '. I tried this code:

df$col <- replace_na(df$col, '')

And this code:

df$col <- replace_na(df$col, col = c(''))

But both approaches result in the following output:

 Error in UseMethod("replace_na") : 
  no applicable method for 'replace_na' applied to an object of class "character"

I know this is a common operation and I am sure the solution is simple. What is the syntax for replacing NAs with a string? (Or, what is the best solution to my problem of standardizing the ' ' and NA values?)

  • Look http://stackoverflow.com/questions/24172111/change-the-blank-cells-to-na – tatxif Mar 25 '17 at 16:06
  • Right syntax: `df <- replace_na(df, list(col = ""))`. I would rather do the converse, ie replace the empty strings with `NA`s like this: `df$col[df$col == ""] <- NA` (but it depends on the context). – Scarabee Mar 25 '17 at 16:08
  • Thanks, that makes sense. I initially did want to replace the blanks with NAs, so you have answered both of my questions. – James Meservy Mar 27 '17 at 18:28

2 Answers2

2

Try this:

df$col[is.na(df$col)] <- ''
2

The arguments to tidyr::replace_na() are

function (data, replace = list(), ...) 

The full data goes in the first argument (data), then you add a name-value pair in the list of the second argument (replace).

tidyr::replace_na(df, list(col = ""))
#    col
# 1     
# 2     
# 3 text
# 4     
# 5     
# 6 text
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • This explanation is perfect, thanks. Is the :: syntax from base R? I am not familiar with that yet. – James Meservy Mar 27 '17 at 18:29
  • @JamesMeservy - `::` is an operator used to get the function `replace_na` from the namespace `tidyr` without loading the package. I thought you wanted to use `replace_na()`, since that's what you used in the question and you used the [tag:tidyr] tag. – Rich Scriven Mar 27 '17 at 23:07