Hi all, Does anybody know whether one can nest an 'if' statement in a 'for' loop. According to the results of my code, the for loop is performed first, but I'm not sure I got something else wrong with my code. I'm trying to perform the if statement for each step of the for loop. Thanks in advance. Best regards, Sebastian
Here is an example:> for(i in 1:10) if (i %% 2) print(i) else print("even")[1] 1 [1] "even" [1] 3 [1] "even" [1] 5 [1] "even" [1] 7 [1] "even" [1] 9 [1] "even" Date: Sat, 21 Feb 2004 23:23:45 -0600 From: Sebastian Luque <sluque at mun.ca> To: <r-help at stat.math.ethz.ch> Subject: [R] nested loop Hi all, Does anybody know whether one can nest an 'if' statement in a 'for' loop. According to the results of my code, the for loop is performed first, but I'm not sure I got something else wrong with my code. I'm trying to perform the if statement for each step of the for loop. Thanks in advance. Best regards, Sebastian ______________________________________________ R-help at stat.math.ethz.ch mailing list https://www.stat.math.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html As AttachmentAs Inline Text Move to Folder----- Folders ------InboxDraftsSentTrashBulk Mail---- My Folders ----RRcomRtmpSaved < Prev Next > Back to Inbox Print View Full Header Make My Way Your Home Page | Spread the Word My Settings: Overview | Search | Email | Chat | Portfolio | Calendar | Groups | Profile IMPORTANT: We do not present our users with pop-ups, banners or any other non-text advertising. Nor do we send email to our users. If you see or receive one of these items, it is coming from an outside source, either as a result of something you have previously downloaded or as an "exit" pop-up from the site you just visited. It is not coming from our site. Privacy Policy Terms of Service Partner with Us Our Mission Sign In Sign Out Help Center © 2002-2004 My Way
On Sat, 21 Feb 2004 23:23:45 -0600, you wrote:>Hi all, > >Does anybody know whether one can nest an 'if' statement in a 'for' >loop. According to the results of my code, the for loop is performed >first, but I'm not sure I got something else wrong with my code. I'm >trying to perform the if statement for each step of the for loop. Thanks >in advance.Yes, no problem:> for (i in 1:10) {+ if (i %% 2 == 0) cat(i, ' is even!\n') + } 2 is even! 4 is even! 6 is even! 8 is even! 10 is even! If you leave off the braces ("{ }"), my example will still work, but multi-line examples won't: only the first line will be repeated in the for loop. Duncan Murdoch