jeudi 6 juin 2019

R for loop ignores conditional if statement

I'm working with a dataset in which I need R to skip over it if the value is NOT missing. I've tried making a for loop, but R ignores my logic. I've seen other for loop posts, but they do not involve the conditional being ignored.

Here's a sample dataset:

library(dplyr)
  my_problem <- tibble(name = c("Joe", "Joseph", "Joey"),
                       score1 = c(2, 7, 12),
                       score2 = c(NA, 5, 10))

Here's what I want it to look like:

solution <- tibble(name = c("Joe", "Joseph", "Joey"),
                     score1 = c(1, 7, 12),
                     score2 = c(NA, 5, 10),
                     score2edit = c(.30103, 5, 10))

And here's my for loop with a log10() transformation on score1 if the score2 column is NA. However, for some reason, the code ignores my if statement and jumps straight to the else.

  for(i in 1:nrow(my_problem)) {
    if(is.na(my_problem$score2[i])) {
      my_problem$score2edit <- log10(my_problem$score1)
    } else {
      my_problem$score2edit <- my_problem$score2
    }
  }

Thank you! If you could also explain why this loop isn't working, it would be very helpful.

Aucun commentaire:

Enregistrer un commentaire