首页 > 解决方案 > case_when 使用公式

问题描述

我正在使用iris数据框,我想创建一个列,Result,具有以下条件:

如果Sepal.Length >=5 分配Result=Sepal.Length*Sepal.Width ,否则如果Sepal.Length <5 and Sepal.Length >4.3分配Result=Sepal.Length+Sepal.Width。否则分配Result=Sepal.Length/Sepal.Width

我试过case_when了,但我认为它只有在分配的值是字符串时才有效。

最好的方法是什么?

标签: rdplyr

解决方案


试试这个:

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

推荐阅读