[英]Case_when and mutate using multiple variables
Its my first time using R and I have been trying to transfer code across from SPSS to R, the syntax is creating a new variable in R using multiple conditions from multiple variables.这是我第一次使用 R,我一直在尝试将代码从 SPSS 转移到 R,语法是使用来自多个变量的多个条件在 R 中创建一个新变量。 The equivalent SPSS syntax is:
等效的 SPSS 语法是:
COMPUTE OPEN=0.
DO IF (APP=1).
COMPUTE OPEN = 2.
ELSE IF (SCO12 >= 1 AND SCO12 <= 50).
COMPUTE OPEN = 2.
ELSE IF NOW = 1.
COMPUTE OPEN = 2.
ELSE IF EWEEK =1.
COMPUTE OPEN =2.
ELSE IF ROLL = 1.
DO IF (AT = 1 or AT = 2).
COMPUTE OPEN = 2.
ELSE IF AT = 3.
COMPUTE OPEN = 1.
ELSE IF AT = -8.
COMPUTE OPEN = -8.
ELSE.
COMPUTE OPEN = 2.
END IF.
ELSE IF (APP=-8 OR NOW = -8 OR ROLL = -8 or EWEEK=-8).
COMPUTE OPEN = -8.
ELSE IF (AGE=16 and (SCO12=97 or SCO12=-9)) .
COMPUTE OPEN =-8.
ELSE.
COMPUTE OPEN = 1.
END IF.
The R code i've got so far is到目前为止我得到的 R 代码是
OD21 %>% mutate(OPEN = case_when(APP = 1 ~ 2,
(SCO12 >=1 & SCO12 <=50) ~ 2,
NOW = 1 ~ 2,
EWEEK = 1 ~ 2,
ROLL = 1 & (AT = 1 | AT = 2) ~ 2,
ROLL = 1 & AT = 3 ~ 1,
ROLL = 1 & AT = -8 ~ -8)
However I can work out how to continue on from this?但是我可以弄清楚如何继续吗?
If I understand your SPSS code correctly (not an SPSS user myself)如果我正确理解您的 SPSS 代码(我自己不是 SPSS 用户)
OD21 <- OD21 %>%
mutate(OPEN = case_when(
# "OPEN" will be == 2
APP == 1 ~ 2,
(SCO12 >= 1 & SCO12 <= 50) ~ 2,
NOW == 1 ~ 2,
EWEEK == 1 ~ 2,
ROLL == 1 & (AT == 1 | AT == 2) ~ 2,
ROLL == 1 & AT != 1 & AT != 2 & AT != 3 & AT != -8 ~ 2,
# "OPEN" will be == -8
ROLL == 1 & AT == -8 ~ -8,
APP == -8 | NOW == -8 | ROLL == -8 | EWEEK == -8 ~ -8,
AGE == 16 & (SCO12 == 97 | SCO12 == -9) ~ -8,
# "OPEN" will be == 1
TRUE ~ 1
)
Not tested as I don't have a reproducible example.没有测试,因为我没有可重现的例子。
==
(Not with a single =
, which is a different operator).==
检查两个数字之间的等价性(不是使用单个=
,这是不同的运算符)。TRUE ~
at the end to cover all cases that were not covered in previous statementsTRUE ~
来涵盖之前语句中未涵盖的所有情况mutate
won't save your dataset unless you re-assign <-
the object<-
object,否则mutate
不会保存您的数据集
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.