Pergunta

I try to use ifelse to assign values to several variables through a loop but it gives me NAs for all cases and variables.

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".

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. 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?

Foi útil?

Solução

To test for NA, you need to use the is.na function. 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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top