对列中的多个值使用ifelse语句 [英] Using ifelse statement for multiple values in a column

查看:58
本文介绍了对列中的多个值使用ifelse语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

其中SCHEach列中的值基于Type列中的值.如果类型"列中的值为16、17、21或22,则SCHeach列中的值应为1.对于类型"列中的任何其他值,SCHEach值应为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.

现在我正在使用以下

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

我是R的新手,想知道是否有一种方法可以不必在16,17,21和22处分别键入以下内容?

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'

推荐答案

> 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

这篇关于对列中的多个值使用ifelse语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆