rfor-loopif-statementnaclass-factory

Double for loop with ifelse() is not working properly in R


I am trying to run through each columns of my dataframe and convert "unknown" values to NAs. I tried the following code:

for (i in seq(length(df))) {
 for (j in seq(nrow(df))) {
      ifelse(df[,i][j] == "unknown", NA, df[,i][j])
 }
}

It, however, has not changed any values. The columns I am trying to alter are factors so I also tried:

for (i in seq(length(df))) {
 x <- class(df[,i])
 as.character(df[,i])
 for (j in seq(nrow(df))) {
      ifelse(df[,i][j] == "unknown", NA, df[,i][j])
 }
 class(df[,i]) <- x
}

to no avail. There is no error obtained and the code appears to run without problem; only the values remain as "unknown.


Solution

  • We can try:

    df[df == "unknown"] = NA
    

    This assumes that all your columns are character and not factor.