title: ifelse within loop in R
body: <p>I try to use ifelse to assign values to several variables through a loop but it gives me NAs for all cases and variables.</p>
  
  <p>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. 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".</p>
  
  <p>My code looks like this:</p>
  
  <pre><code>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="")] &lt;- ifelse(
        olddata[,paste("q08pa",spell,sep="")]==age &amp;
          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
    }
  }
  </code></pre>
  
  <p>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. Somehow, I get a data frame full of NAs after running this code. What is the problem here? Is it with ifelse? Is it anything related to the scope and ifelse not being able to access the loop variables correctly?</p>