[英]How do I create a new variable based on two categorical values in R?
I have a marital status variable, with possible values "Married" "Divorced" "Widowed" "Separated" "Never Married" "Part of an unmarried couple".我有一个婚姻状况变量,可能的值是“已婚”“离婚”“丧偶”“分居”“未婚”“未婚夫妇的一部分”。
I wish to create a new variable called single , where if marital is "Married" OR "Part of an unmarried couple", it is classified as "Not Single", else "Single".我希望创建一个名为single的新变量,如果marital是“已婚”或“未婚夫妇的一部分”,则将其归类为“Not Single”,否则归类为“Single”。
Was thinking something like below, but with some kind of OR operator ie "Married" OR "Part of an unmarried couple".正在考虑类似下面的内容,但使用某种 OR 运算符,即“已婚”或“未婚夫妇的一部分”。
dataset <- dataset %>%
mutate(single = ifelse(marital == “Married”, "Not Single", " Single"))
I am very new to R and hope someone can help.我对 R 很陌生,希望有人能提供帮助。 Thanks for your time!
谢谢你的时间!
You already found a good solution, but since you specifically asked about the or operator, in R it's |
您已经找到了一个很好的解决方案,但是由于您特别询问了 or 运算符,因此在 R 它是
|
. .
dataset <- dataset %>%
mutate(single = ifelse( marital == "Married" | marital == "Part of an unmarried couple",
"Not single",
"single")
Note that its |
请注意,它的
|
, not ||
, 不是
||
: :
& and && indicate logical AND and |
& 和 && 表示逻辑 AND 和 | and ||
和 || indicate logical OR.
表示逻辑或。 The shorter form performs elementwise comparisons in much the same way as arithmetic operators.
较短的形式执行元素比较的方式与算术运算符大致相同。 The longer form evaluates left to right examining only the first element of each vector.
较长的形式从左到右评估,仅检查每个向量的第一个元素。 Evaluation proceeds only until the result is determined.
仅在确定结果之前进行评估。 The longer form is appropriate for programming control-flow and typically preferred in if clauses.
较长的形式适用于编程控制流,通常在 if 子句中首选。
(Copied from https://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html ) (复制自https://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.