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

Switch on factors

- [Instructor] Last week, we talked about using the Switch Statement instead of If, Then, Else. And there's one thing you want to be aware of when using Switch, and that's switching against factors. You can do it, but it behaves in a way that you might not expect. So, let's take a minute to examine how switching with factors works. First of all, we'll need a vector with factors in it, and in line three create Bucket of Fruit. It's a factor with three levels, and we can look at the internals on line five. I'm using unclass(BucketOfFruit), and what that tells us is one, two, three, two, which is the factors that are actually stored in Bucket of Fruit followed by the levels Apple , Banana, and Mango. So, in this case, Bucket of Fruit actually represents itself as Apple , which is the first value, Banana, the second value, Mango, the third value, and then Banana, which is the second value. So that's a factor. Now, keep that in mind as we look at switching on factors. In line seven I've created a function called Fruit Color, and what Fruit Color does is switch against a fruit. So, if I give the function Fruit Color the name of a fruit it will return the color of that fruit. So let's go ahead and define that function. And now, if I run that using fruitColor(bucketOfFruit), and I'm going to use the first element of Bucket of Fruit. You'll see that I get Apple is Red, but I also receive a warning message. And what that warning message is saying is that, okay R is willing to do this, it is willing to switch against a factor, but perhaps you want to switch against the actual character string that the factor represents. In this case, Bucket of Fruit subset one is Apple . The factor is passed into Fruit Color and returns Red. But you may be wanting to switch that as the string Apple instead of the factor Apple . So, this is a little bit confusing. You may want to take a look at this, and it may generate some unexpected bugs in some of the code that you're creating, but it can be done.

Contents