'How to use or (" | ") in ifelse in r programming for categorial value
For example, I want to make a subcategory from column data1 to data2. It will categorize if A or B, and it will put a value of 1 for it, else 0.
Project_R2 $data2 = ifelse (Project_R2 $data1 =="A" | "B", 1,0).
This code is not working for me.
Solution 1:[1]
There are more options, so you can try this:
Project_R2$data2 = ifelse(Project_R2$data1 =="A" | Project_R2$data1 == "B", 1,0)
And as @markus mentioned in the comments, you can also use this:
Project_R2$data2 = ifelse(Project_R2$data1 %in% c("A", "B"), 1,0)
Solution 2:[2]
With %in% you can test if elements are part of a set which makes it equivalent to | (as recommended by @Markus). It gives the same result
Project_R2 <- data.frame(data1 = c("A", "C", "B", "D", "B", "A", "C", "D"))
Project_R2$data2 = ifelse(Project_R2$data1 %in% c("A", "B"), 1, 0)
Project_R2$data2
#> [1] 1 0 1 0 1 1 0 0
Or even shorter but a bit less obvious to understand (as.integer coerces TRUE to 1 and FALSE to `0``)
Project_R2$data2 = as.integer(Project_R2$data1 %in% c("A", "B"))
Project_R2$data2
#> [1] 1 0 1 0 1 1 0 0
Created on 2022-04-15 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Jan |
