My problem is related to data manipulation: on the basis of the existing variables in a given data set, I would like to create new ones. Bonus points for performance as well as code readability.
Let's consider a reproducible example for the famous "iris" data set. My goal is to create a new variable, which can be described by the following set of conditions:
- if species="setosa" or species="virginica" and sepal.length < 5 then new variable = "Species1",
- if (species="setosa" or species="virginica") and 5<= sepal.length < 10 then new variable = "Species2",
- if (species="setosa" or species="virginica") and sepal.length >= 10 then new variable = "Species3",
- otherwise, new variable = species (in this case "versicolor").
In order to achieve this, I have written the following conditional instructions:
iris$Speciec2 <- ifelse(iris$Species %in% c("setosa", "virginica"),
ifelse(iris$Sepal.Length < 5, "Species1",
ifelse(iris$Sepal.Length >= 5 & iris$Sepal.Length < 7,
"Species2", "Species3")), as.character(iris$Species))
and it's really hard to read. I wonder if there are any better solutions.