通过mutate case_when通过多个条件创建新变量

问题描述 投票:0回答:1

Hi希望在dyplr,mutate和case_when的特定条件下,通过2个变量(WHR和sexe)创建一个新的变量/列(WHRcat)。

数据:

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

r variables dplyr mutate case-when
1个回答
0
投票

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

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)) 
© www.soinside.com 2019 - 2024. All rights reserved.