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
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
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