r - 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
了,但我认为它只有在分配的值是字符串时才有效。
最好的方法是什么?
解决方案
试试这个:
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
推荐阅读
- javascript - select2 使用 ajax 预定义的渲染项目
- rxjs - RXJS:如何从 Promise 限制 Observable
- python - 在一个字符字段中使用两个模型字段组合的 Django ModelForm
- mysql - 将 Oracle 查询转换为 MySQL 查询
- cocos2d-x - 为什么调用 setFlipped(true) 时动画没有水平翻转?
- cassandra - 如何从某个节点查询 Cassandra 并仅从该节点自己获取数据?
- variables - Activiti BPMN - 如何在已完成任务的变量/表达式中传递用户名?
- javascript - 选中复选框时PHP更改查询
- javascript - 如何通过带有geojson的谷歌地图的setStyle函数获得虚线
- c# - Can't return byte[ ] with security=Message