samedi 3 novembre 2018

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.

Aucun commentaire:

Enregistrer un commentaire