1

I have a table of survey questions:

ques <- data.frame(stringsAsFactors=F,
         question_id=c("q1","q2"),
         question_nm=c("computer_hrs","exercise_hrs"),
         question_txt=c("How many hours did you spend last week on a computer?",
                        "How many hours did you spend last week on exercise?")
        )

The question_nm is a short description string, already checked to be valid as a variable name.

I have a table of responses:

resp <- data.frame(stringsAsFactors=F,
  respondent_id=c(1,2),
  respondent_nm=c("Joe Programmer","Jill Athlete"),     
  q2=c(1,100), #column order in resp not guaranteed same as row order in ques
  q1=c(100,1) 
)

In order to have meaningful response variable names I wish to replace the names q1 and q2 with computer_hrs and exercise_hrs.

Note that you would get the wrong answer with:

names(resp)[ques$question_id %in% names(resp)] <- ques$question_nm #wrong

due to the column order in responses not matching the row order in questions. (I know I could fix that by sorting each order.)

I can do this with a for loop...

for (q in ques$question_id){
  names(resp)[names(resp)==q] <- ques$question_nm[ques$question_id==q]
}

... but given a function that returned the mapping of the elements of ques$question_id to names(resp), similar to %in% but returning the position rather than T/F, I could do it without the For loop. Unfortunately, the only way I know to write that function involves a For loop.

Is there a way to accomplish this replacement without the loop?

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134

1 Answers1

3

Try:

names(resp)[match(ques[,1], names(resp))] <- ques$question_nm
akrun
  • 874,273
  • 37
  • 540
  • 662
  • `match` works. I knew about `%in%` but never realized that it is an interface of `match` that converts the positions returned by `match` to boolean. Thank you. – C8H10N4O2 Jun 20 '14 at 20:07