0

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.

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • 4
    You would better use `%in%`, i.e. `ifelse(Project_R2$data1 %in% c("A", "B"), 1,0)` or maybe `as.integer(Project_R2$data1 %in% c("A", "B"))` – markus Apr 15 '22 at 13:10
  • 1
    Relevant: [Test if a vector contains a given element](https://stackoverflow.com/questions/1169248/test-if-a-vector-contains-a-given-element) – markus Apr 15 '22 at 13:14

2 Answers2

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)
Quinten
  • 35,235
  • 5
  • 20
  • 53
1

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)

Jan
  • 4,974
  • 3
  • 26
  • 43