C8H10N4O2
C8H10N4O2

Reputation: 19005

Batch-rename variables in R without For loop

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?

Upvotes: 1

Views: 573

Answers (1)

akrun
akrun

Reputation: 887158

Try:

names(resp)[match(ques[,1], names(resp))] <- ques$question_nm

Upvotes: 3

Related Questions