简体   繁体   English

用缺失值重新编码R中的变量

[英]Recoding a variable in R with missing values

I'm having difficulty understanding why my code to create a dummy variable isn't working. 我很难理解为什么我的创建虚拟变量的代码无法正常工作。 My data contains some NA values and is of the following form: 我的data包含一些NA值,其格式如下:

Year   Month   Var1  Var2
2006    9      278   345
2006    10     251   857
2006    11     254   678
.      .       .     . 
.      .       .     .
2015   12      230   641
2016    1      647    268
2016    2      NA    785
2016    3      NA    419
.      .       .     . 
.      .       .     .
2016   6      NA     369

I'm trying to create a seasonal additive dummy variable that will equal one for December starting in 2014 and continuing on. 我正在尝试创建一个季节性加性虚拟变量,该变量将从2014年开始一直持续到12月。 I can't understand why the following code doesn't work. 我不明白为什么下面的代码不起作用。

SAout <- ifelse(data$Year<= 2014 & data$Month == 12, 1, 0)

For any time after Jan 2016 SAout takes the value NA which makes no sense to me since data$Year is still greater than 2014 . 在2016年1月之后的任何时间, SAout的取值NA都对我来说毫无意义,因为data$Year仍大于2014

SAout
[1]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 [41]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
 [81]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0  0  0  0  1  0 NA NA NA NA NA NA

EDIT 编辑

I can create the variable I want with the following 我可以使用以下内容创建所需的变量

data$SAout <- ifelse(data$Year >= 2014 & data$Month == 12, 1, 0)
data$SAout[is.na(data$SAout)]<-0

However I don't understand why the second line of code should be necessary. 但是我不明白为什么第二行代码是必要的。

Its be because you are trying to create a dummy variable with 2 conditions. 这是因为您尝试创建具有2个条件的虚拟变量。

  1. data$year > 2013 data $ year> 2013
  2. data$month == 12 data $ month == 12

In your code it says if year and month is equal to 12. 在您的代码中,它说明年和月是否等于12。

Rather try the following code 而是尝试以下代码

data$SAout<-ifelse(data$year >=2014 & data$month==12,1,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM