在R中批量重命名变量,不需要For循环



我有一个调查问题表:

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?")
        )

question_nm是一个简短的描述字符串,已经被检查为有效的变量名。

我有一个响应表:

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) 
)

为了有意义的响应变量名称,我希望将名称q1q2替换为computer_hrsexercise_hrs

注意,使用

会得到错误的答案。
names(resp)[ques$question_id %in% names(resp)] <- ques$question_nm #wrong

由于回答中的列顺序与问题中的行顺序不匹配。(我知道我可以通过对每个顺序进行排序来解决这个问题。)

我可以用for循环来做这个…

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

…但是给定一个函数返回ques$question_id元素到名称(resp)的映射,类似于%in%,但返回位置而不是T/F,我可以在没有For循环的情况下做到这一点。不幸的是,我知道编写该函数的唯一方法是使用For循环。

有没有一种方法可以在没有循环的情况下完成这个替换?

尝试:

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

相关内容

最新更新