user6340762 user6340762 - 1 month ago 7
R Question

Using ifelse statement for multiple values in a column

I have a table with approximately 3000 rows with data in the form of :

Number Type
10001 0
10005 7
10006 0
10007 14
10012 16
10022 14
10023 0
10024 0
10029 7
10035 17
10045 14


I want to add a third column so that the table looks like :

Number Type SCHEach
10001 0 0
10005 7 0
10006 0 0
10007 14 0
10012 16 1
10022 14 0
10023 0 0
10024 0 0
10029 7 0
10035 17 1
10045 14 0


where values in the SCHEach column are based on values in the Type column. If values in the Type column are 16,17,21, or 22, values in the SCHeach column should be 1. For any other values in the Type column, SCHEach values should be 0.

Right now I'm using the following

library(dplyr)
schtable$SCHEach = ifelse(
schtable$Type == 16 |
schtable$Type == 17 |
schtable$Type == 21 |
schtable$Type == 22, 1, 0)


I am new to R and wanted to know if there is a way to do it without having to type the following separately for 16,17,21,and 22?

schtable$Type == 'number'

Answer
> mydf$SCHEach <- ifelse(mydf$Type %in% c(16,17,21,22),1,0)
> mydf
   Number Type SCHEach
1   10001    0       0
2   10005    7       0
3   10006    0       0
4   10007   14       0
5   10012   16       1
6   10022   14       0
7   10023    0       0
8   10024    0       0
9   10029    7       0
10  10035   17       1
11  10045   14       0