アンケートの質問の表があります:
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)
)
意味のある応答変数名を付けるために、名前をq1
andに置き換えたいと思います。 q2
computer_hrs
exercise_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 ループを使用することだけです。
ループなしでこの置換を行う方法はありますか?