0

I'm trying to change N/A in a data frame to 0, I tried this:

adv[is.na(adv)]=0

and I got this:

In [<-.factor(*tmp*, thisvar, value = 0) : invalid factor level, NA generated

  • 1
    If `adv` is a frame, then you should likely be doing this to one or more columns of said frame instead of the frame as a whole. While the code works, there is room for ambiguity here if you have non-numeric columns. – r2evans Nov 19 '19 at 21:58

2 Answers2

1

From the error message, there are factor columns, which needs to be converted to character first

i1 <- sapply(adv, is.factor)
adv[i1] <- lapply(adv[i1], as.character)

Now, it can be converted to 0

adv[is.na(adv)] <- 0

is.na works only when the value is NA and not "N/A". It is better to read with na.strings in read.csv/read.table

adv <- read.csv('file.csv', na.strings = "N/A", stringsAsFactors = FALSE)
adv[is.na(adv)] <- 0
akrun
  • 874,273
  • 37
  • 540
  • 662
1

try this:

as.numeric(is.na(adv))