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.

Switch

Switch

- [Instructor] A switch statement is a way to express a complex if then else statement. As an example, let's look at lines five through twelve. What I've done, is first of all, created a vector called testme and assigned three to that vector. Then, in line six through twelve I'll test that vector against multiple values. It returns X number one and what you can see is that the first line says if testme is equal to three then print X number 1. So, that's an if then statement but maybe a switch statement would be clearer. And here's how a switch statement looks in R. Line 18 starts with switch and then the value that we're going to switch against, and you'll notice that it's a numeric value, and then the actions against that value. So, in this case, if I run line 18 I'll get the third action which is the third value. So, switch against a number just simply selects an action based on the switch and value. What about switching against a string? If you look at line 30 through 33 you can…

Contents