0

I am trying to replace values with NA based on a condition. I have written the following code which works fine:

df <- df %>% 
mutate(var1 = ifelse(years > 0, NA, var1)

I need run this code for 80+ different variables, so I am trying to use a for loop (instead of copy-pasting). I have tried the following code, but it doesn't work

for(i in c(13:100))
   {df <- df %>% 
         mutate(i = ifelse(df$years > 0, NA, i))}

Ideally, the output of the loop will be stored back in the original dataframe. Thank you so much, any help is greatly appreciated!

rookie11
  • 5
  • 3

1 Answers1

0

This should work directly :

df[df$years > 0, 13:100] <- NA

Consider this small example :

set.seed(123)
df <- data.frame(years = c(-1, 1, -3, -4, 9), var1 = rnorm(5), var2 = rnorm(5))
df

#  years        var1       var2
#1    -1 -0.56047565  1.7150650
#2     1 -0.23017749  0.4609162
#3    -3  1.55870831 -1.2650612
#4    -4  0.07050839 -0.6868529
#5     9  0.12928774 -0.4456620
df[df$years > 0, 2:3] <- NA
df

#  years        var1       var2
#1    -1 -0.56047565  1.7150650
#2     1          NA         NA
#3    -3  1.55870831 -1.2650612
#4    -4  0.07050839 -0.6868529
#5     9          NA         NA
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213