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

R: What am I doing wrong in this for-loop with an if-else statement?

Sample data:

df <- data.frame(apples = c(1, 5, 3),
                 oranges = c(5, 3, 5))

Problem:

for(i in names(df)){
  
  if(sum(df$i == 5) == 1){
    
    print(paste("There is only 1 occurance of 5 fruit for", i))
    
  } else {
    
    print(paste("There is more than 1 occurance of 5 fruit for", i))
    
  }
}

this gives me

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

[1] "There is more than 1 occurance of 5 fruit for apples"
[1] "There is more than 1 occurance of 5 fruit for oranges"

however…

> sum(df$apples == 5)
[1] 1
> sum(df$oranges == 5)
[1] 2

My expected output:

[1] "There is only 1 occurance of 5 fruit for apples"
[1] "There is more than 1 occurance of 5 fruit for oranges"

I suspect it’s some sort of syntax issue, or am I missing something more obvious?

>Solution :

You need to use df[[i]] not df$i in your loop, otherwise it is finding variable i in the dataframe. df$i is NULL. sum(NULL == 5) is 0. You always do that else bit.

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