简体   繁体   中英

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".

Was thinking something like below, but with some kind of OR operator ie "Married" OR "Part of an unmarried couple".

dataset <- dataset %>%
mutate(single = ifelse(marital == “Married”, "Not Single", " Single"))

I am very new to R and hope someone can help. Thanks for your time!

You already found a good solution, but since you specifically asked about the or operator, in R it's | .

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 || 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.

(Copied from https://stat.ethz.ch/R-manual/R-devel/library/base/html/Logic.html )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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