Search code examples
rloopsif-statement

for loop and if else


df_test2 <- data.frame(test1=c("in", "out"), test2=c(1:2))

> df_test2
  test1 test2
1    in     1
2   out     2

for (i in df_test2$test1) {
  for (j in df_test2$test2) {
    if (i="in") {
      print(j + 1)
    } else {
      print(j - 1)
    }
  }

I ran the above code and nothing returned while I was expecting see the outcome being 2 and 1. Mind telling if I am using the wrong loop technique?


Solution

  • I would do it without a for loop

    > with(df_test2, ifelse(test1 == "in", test2+1, test2-1))
    [1] 2 1
    

    Note that = is an assignment operator equivalent to <- and you want to do a logical comparison, so you should use == instead.

    If you want for whatever reason a for loop, then you can write it using just one index for selecting rows:

    for (i in seq_len(nrow(df_test2))){
      if(df_test2[i, 1] == "in"){
        print(df_test2[i, 2] + 1)
      } else {
        print(df_test2[i, 2] - 1)
      }
    }