1

In R, I'm using a for loop with an if statement to replace all values in a dataframe that fall outside of a certain range.

for (i in seq_along(df$Age)) {
  if (df$Age[[i]] > 90 || df$Age[[i]] < 16) {
    df$Age[[i]] <- NA
  }
}

This seems like clunky code. Is there a faster, easier way to do this?

1 Answers1

2

Yes! There's a command called replace:

df$Age <- with(df, replace(Age, Age > 90 | Age < 16, NA)) 
Jake Fisher
  • 3,220
  • 3
  • 26
  • 39
  • 1
    I have four reference books on R that I read through, and I searched extensively online with phrases like "R replace," and for whatever reason, I wasn't able to find that simple solution... so thank you! Much appreciated. – EmotionResearcher Jul 25 '18 at 15:02