DD chen
DD chen

Reputation: 189

case_when with formula

I am working with the iris dataframe, and I want to create a column, Result, with the following conditions:

if Sepal.Length >=5 assign Result=Sepal.Length*Sepal.Width else if Sepal.Length <5 and Sepal.Length >4.3 assign Result=Sepal.Length+Sepal.Width. else assign Result=Sepal.Length/Sepal.Width

I tried case_when, but I think it only works if the assigned value is a string.

What's the best way to do that?

Upvotes: 0

Views: 1788

Answers (1)

jyjek
jyjek

Reputation: 2707

Try this one :

library(dplyr)
iris %>% 
   mutate(Result = case_when(
     Sepal.Length >=5 ~ Sepal.Length*Sepal.Width,
     Sepal.Length <5 & Sepal.Length >4.3 ~ Sepal.Length+Sepal.Width,
     TRUE ~ Sepal.Length/Sepal.Width
   ))
    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species    Result
1            5.1         3.5          1.4         0.2     setosa 17.850000
2            4.9         3.0          1.4         0.2     setosa  7.900000
3            4.7         3.2          1.3         0.2     setosa  7.900000
4            4.6         3.1          1.5         0.2     setosa  7.700000
5            5.0         3.6          1.4         0.2     setosa 18.000000
6            5.4         3.9          1.7         0.4     setosa 21.060000
7            4.6         3.4          1.4         0.3     setosa  8.000000
8            5.0         3.4          1.5         0.2     setosa 17.000000
9            4.4         2.9          1.4         0.2     setosa  7.300000
10           4.9         3.1          1.5         0.1     setosa  8.000000

Upvotes: 4

Related Questions