Using ifelse() Statements

The following code will change the representation of the three species to numbers:

iris$Species2 <- ifelse(iris$Species == "setosa", 1,ifelse(iris$Species == "versicolor", 2, 3))

We can verify if it has worked by running the table() function as follows (more on this function in the next section!):

table(iris$Species)

Thus, we will get the following output:

We can also execute the following code to verify whether the representation has changed:

table(iris$Species2)

Here is the output that we will get:

Get R Programming Fundamentals now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.