简体   繁体   English

R循环中的ifelse

[英]ifelse within loop in R

I try to use ifelse to assign values to several variables through a loop but it gives me NAs for all cases and variables. 我尝试使用ifelse通过循环将值分配给多个变量,但是它为所有情况和变量提供了NA。

I have one dataset of occupational histories (all jobs one has had), where each job is coded as "q08dXX" were XX stands for numbers from 01 to 16. Each job has a starting age, stored in a variable "q08paXX" where XX stands for numbers from 12 to 70. I want to create variables job12 to job70, standing for the current job at a given year for all respondents of the survey. 我有一个职业历史数据集(一个职业所有的职业),其中每个职业都被编码为“ q08dXX”,XX代表从01到16的数字。每个职业都有一个起始年龄,存储在变量“ q08paXX”中,其中XX代表从12到70的数字。我想创建变量job12到job70,代表给定年份所有调查受访者的当前职位。 After having created a new data frame with the variables job12 to job70 and assigned NAs to all of them, I want to populate them with the real values based on the values of "q08dXX" and "q08paXX". 在使用变量job12到job70创建了一个新的数据框并为它们分配了NA之后,我想使用基于“ q08dXX”和“ q08paXX”的​​值的实际值填充它们。

My code looks like this: 我的代码如下所示:

for (spell in c("01","02","03","04","05",
                "06","07","08","09","10","11","12",
                "13","14","15","16")
){ 
  for (age in 12:70){
      newdata[,paste("job",age, sep="")] <- ifelse(
      olddata[,paste("q08pa",spell,sep="")]==age &
        olddata[,paste("q08pa",spell,sep="")]!=NA, # check if new spell started and if starting time not missing
      olddata[,paste("q08d",spell,sep="")], # assign value of new spell if it started
      newdata[,paste("job",age, sep="")]) # keep existing value if new spell didn't start
  }
}

Here, olddata is the data frame that holds the type of job and the age that job started and new data is the new data frame where I want to create the jobXX variables. 在这里,olddata是保存作业类型和作业开始年龄的数据框,而新数据是我要在其中创建jobXX变量的新数据框。 Somehow, I get a data frame full of NAs after running this code. 以某种方式,运行此代码后,我得到一个充满NA的数据帧。 What is the problem here? 这里有什么问题? Is it with ifelse? 是ifelse吗? Is it anything related to the scope and ifelse not being able to access the loop variables correctly? 是否与作用域有关,并且是否无法正确访问循环变量?

To test for NA , you need to use the is.na function. 要测试NA ,您需要使用is.na函数。 See that: 看到:

> 1 != NA    # bad
[1] NA

> !is.na(1)  # good
[1] TRUE

So in the end, just replace: 所以最后,只需替换:

olddata[,paste("q08pa",spell,sep="")]!=NA

with

!is.na(olddata[,paste("q08pa",spell,sep="")])

and you should be ok. 你应该没事的

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

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