From the course: R for Data Science: Lunch Break Lessons

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

ifelse

ifelse

R has a ternary operator for if-then-else that can make your code a little bit cleaner and easier to read. But there are some caveats. So let's take a look at if-else. First, in lines one through six I've set up an if-then-else statement just as an example, and this is the traditional notation. If you run this, if true print Leghorn, else, print Orpington, we'll get Leghorn, no surprise. The ternary operator for this looks like if-else, and then you put in the condition, in this case the condition is always true, then print Leghorn, else print Orpington. And, if I run that, I get exactly the same results as the traditional notation. There's another way to notate this, and it also has a caveat that I'll discuss in just a minute, but it looks like this. If parentheses, true, then Leghorn, space, else, quote, Orpington. And you'll notice that I've removed all of the curly braces and most of the parentheses. When I run that, I get, again, the exact same results as the traditional…

Contents