vendredi 29 janvier 2021

Create new, grouped conditional variable in R

Im trying to create a new variable, which is grouped and has several conditions underlying it. E.g. using the iris dataset:

I want to add a new column, grouped by species and contains information about the size. The outcome is expected to be a factor variable with levels "small", "medium" and "large".

Here's an example:

data(iris)
data %>% 
  dplyr::group_by(Species) %>% 
  dplyr::mutate(Size =
                  if_else(Sepal.Length <= 5.1 ~ "small",
                          Sepal.Length <= 5.8 & > 5.1 ~ "medium",
                          Sepal.Length > 5.8 ~ "large")
                ) 

It doesn't work. Apparently there's

an unmatched closed bracket ")"

Now, I am aware of other solutions, e.g. using Base R's ifelse function, but I'm trying to find an elegant way to express myself using tidyverse-style code. Can anyone help? I would be happy about any solutions using tidyverse code. Doesn't matter what function it is.

Aucun commentaire:

Enregistrer un commentaire