Search code examples
rfor-loopdatasetnested-loops

How to use nested loops in R to change values?


I have a data set where I want all 1's to be 0's and anything over 1 to be 1's. I've tried using parentheses instead of brackets.

for (i in 1:nrow(StudentDrugs)){
  for(j in 1:ncol(StudentDrugs)){
    ifelse([i,j] == 1, 0, 1)
  }
}

I get: Error: unexpected '[' in: " for(j in 1:ncol(StudentDrugs)){ ifelse(["


Solution

  • As you didn't yet provide an example dataset, examples below use mtcars.

    With base R, rapply and ifelse:

    rapply(mtcars,f = function(x) ifelse(x==1,0,ifelse(x>1,1,x)),how = 'replace')
    
                        mpg cyl disp hp drat wt qsec vs am gear carb
    Mazda RX4             1   1    1  1    1  1    1  0  0    1    1
    Mazda RX4 Wag         1   1    1  1    1  1    1  0  0    1    1
    Datsun 710            1   1    1  1    1  1    1  0  0    1    0
    Hornet 4 Drive        1   1    1  1    1  1    1  0  0    1    0
    Hornet Sportabout     1   1    1  1    1  1    1  0  0    1    1
    ...
    

    With dplyr and case_when.

    library(dplyr)
    mtcars %>% mutate(across(everything(),function(x) case_when(x==1 ~ 0, x > 1 ~ 1, T ~ x )))
    
                        mpg cyl disp hp drat wt qsec vs am gear carb
    Mazda RX4             1   1    1  1    1  1    1  0  0    1    1
    Mazda RX4 Wag         1   1    1  1    1  1    1  0  0    1    1
    Datsun 710            1   1    1  1    1  1    1  0  0    1    0
    Hornet 4 Drive        1   1    1  1    1  1    1  0  0    1    0
    Hornet Sportabout     1   1    1  1    1  1    1  0  0    1    1
    ...