Using ifelse statement for multiple values in a column

佐手、 提交于 2021-02-04 19:54:22

问题


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'

回答1:


> 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


来源:https://stackoverflow.com/questions/40330343/using-ifelse-statement-for-multiple-values-in-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!