通过 mutate case_when 通过多个条件创建新变量 [英] Create new variable by multiple conditions via mutate case_when

查看:21
本文介绍了通过 mutate case_when 通过多个条件创建新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,想在特定条件下使用 dyplr、mutate 和 case_when 创建一个由 2 个变量(WHR 和 sexe)组成的新变量/列(WHRcat).

Hi want to create a new variable/column (WHRcat) by 2 variables (WHR and sexe) under a certain condition wth dyplr, mutate and case_when.

数据:

WHR   sexe  WHRcat (new variable)
1.5    1
2.8    2
0.2    2
0.3    1
1.1    1

我的代码:

test<- test%>% mutate(WHRcat = case_when((WHR >= 1.02 & sexe = 1) ~ 1,
                                         (WHR < 1.02 & sexe = 1) ~ 2,
                                         (WHR >= 0.85 & sexe = 2) ~ 3,
                                         (WHR < 0.85 & sexe = 2) ~ 4,
                                          TRUE ~ 0)) 

虽然不起作用.

错误:

> test<- test%>% mutate(WHRcat = case_when((WHR >= 1.02 & sexe = 1) ~ 1,
+                      (WHR < 1.02 & sexe = 1) ~ 2,
+                      (WHR >= 0.85 & sexe = 2) ~ 3,
+                      (WHR < 0.85 & sexe = 2) ~ 4,
+                       TRUE ~ 0))
Error in WHR >= 1.02 & sexe = 1 : could not find function "&<-"

我做错了什么?

看看这个可行的例子:

#' # case_when is particularly useful inside mutate when you want to
#' # create a new variable that relies on a complex combination of existing
#' # variables
#' starwars %>%
#'   select(name:mass, gender, species) %>%
#'   mutate(
#'     type = case_when(
#'       height > 200 | mass > 200 ~ "large",
#'       species == "Droid"        ~ "robot",
#'       TRUE                      ~ "other"
#'     )
#'   )

来自 https://github.com/tidyverse/dplyr/blob/master/R/case_when.R

推荐答案

问题在于使用赋值运算符 = 而不是比较 ==

The issue is in the use of assignment operator = instead of comparison ==

library(dplyr)
test<- test%>% 
       mutate(WHRcat = case_when((WHR >= 1.02 & sexe == 1) ~ 1,
                                         (WHR < 1.02 & sexe == 1) ~ 2,
                                         (WHR >= 0.85 & sexe == 2) ~ 3,
                                         (WHR < 0.85 & sexe == 2) ~ 4,
                                          TRUE ~ 0)) 

这篇关于通过 mutate case_when 通过多个条件创建新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆