对列中的多个值使用ifelse语句

时间:2016-10-30 14:53:54

标签: r if-statement dplyr

我有一个包含大约3000行的表格,数据格式为:

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

我想添加第三列,以便表格如下:

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

其中SCHEach列中的值基于“类型”列中的值。如果Type列中的值为16,17,21或22,则SCHeach列中的值应为1.对于Type列中的任何其他值,SCHEach值应为0.

现在我使用以下

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

我是R的新手,想知道是否有办法做到这一点,而无需为16,17,21和22单独输入以下内容?

schtable$Type == 'number'

1 个答案:

答案 0 :(得分:5)

> 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
相关问题