Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

for loop and if else in R

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? Many thanks.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 reasong 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)
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading