R365: Day 38 – If Else statements in R

One way to logically organize code is to perform if-then-else statements. You can do these sorts of statements in most coding languages and even in Excel (!), which is a really easy format if you just need to do something quickly. The basic gist of if-then-else statements goes something like this:

If (some event or situation is true)

Then (do something)

Else (in all other cases, do this other thing)

These sorts of statements are useful for organizing and quickly analyzing data. In R, you can use these to summarize data or to help add stochasticity to a model. This is probably not the most efficient way to add stochaticity, but it is effective.

Lets pretend that it rains about three days a week. We could use historic data to back this up, but those data only go so far; eventually you need to start forecasting. You can use a fitted model to previous data to try to predict when rain will occur, but these models don’t end up working so well. Depending on your goal, it can be more effective just to model hypothetical weather.

if ( rbinom(1,1,(4/7))>=1 ){ 
} else { 

The output from this will give you back either “Sunny!” or “Rainy!” depending on the results of the rbinom() statement.

If (haha!) that code up there looks really cluttered and you don’t feel like dealing with it, then you can use ifelse() as one statement to do the same thing


I have no idea why people seem to prefer doing the if statement up there, it seems like way more work and less intuitive. It might be that ifelse is less efficient, so if you have a big code it will take longer, but that doesnt really affect me now. Another cool thing is that you can nest if-then-else statements to create some reasonably complex tasks.


Here we nested function within our other ifelse() to say that some of the time there will be thunderstorms instead of sun.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s