简体   繁体   English

dplyr如何计算R中的条件变异?

[英]how calculate a conditional mutate in R with dplyr?

i have this problem. 我有这个问题。 I want calculate a new variable, this variable it conditioned to other variables: 我想计算一个新变量,该变量将其他条件作为条件:

P46A is a variable of level of education and P47 is the years in this level. P46A是教育水平的变量,P47是该水平的年数。

The idea is: 这个想法是:

enter image description here 在此处输入图片说明

And i use the dplyr: 而且我使用dplyr:

Datos %>% mutate(newvariable= if_else(P46A %in% c(-98,-99),NA,
if_else(P46A %in% c(0,1), P47, if_else(P46A %in% c(2:4),P47+3,
if_else(P46A %in% c(5:7,11),P47+16, if_else(P46A %in% c(8,9),P47+23,P47+26))))))

In other words, i want calculate a newvariable dependent of the values in other varaible. 换句话说,我想根据其他变量中的值来计算一个newvariable。 When i run the code R print error. 当我运行代码R打印错误。

Error in mutate_impl(.data, dots) : 
  Evaluation error: `false` must be type logical, not double.

thanks! 谢谢!

You might also trying replacing the if_else statements with a case_when statement. 您也可以尝试用case_when语句替换if_else语句。 It makes for much more legible code. 它使代码更清晰。

Datos %>% mutate(
  newvariable= case_when(
    P46A %in% c(-98, -99) ~ NA_real_,
    P46A %in% c(0, 1) ~ P47,
    P46A %in% c(5:7, 11) ~ P47 + 16,
    P46A %in% 8:9 ~ P47 + 23,
    TRUE ~ P47 + 26
  )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM