サンプルコードの使用:
df <- structure(list(DWFRSS1 = c("Always", "Sometimes", "Never", "Always",
"Sometimes", "Sometimes", "Always", "Sometimes", "Never", "Often",
"Always", "Sometimes", "Sometimes", "Always", "Always"), DWFRSS2 = c("Always",
"Never", "Often", "Always", "Always", "Never", "Always", "Rarely",
"Never", "Often", "Always", "Rarely", "Often", "Never", "Always"
), DWFRSS3 = c("Always", "Always", "Often", "Always", "Always",
"Always", "Always", "Sometimes", "Rarely", "Often", "Always",
"Often", "Always", "Always", "Always"), DWFRSS4 = c("Always",
"Always", "Often", "Always", "Always", "Always", "Always", "Never",
"Often", "Always", "Always", "Sometimes", "Often", "Sometimes",
"Sometimes"), DWFYSS1 = c("Often", "Often", "Always", "Always",
"Always", "Often", "Often", "Rarely", "Sometimes", "Often", "Never ",
"Sometimes", "Sometimes", "Always", "Always"), DWFYSS2 = c("Often",
"Always", "Always", "Always", "Always", "Always", "Sometimes",
"Rarely", "Rarely", "Always", "Always", "Often", "Often", "Always",
"Always"), DWFYSS3 = c("Often", "Often", "Always", "Always",
"Always", "Often", "Never ", "Rarely", "Never ", "Always", "Always",
"Often", "Often", "Always", "Always"), DWFYSS4 = c("Always",
"Always", "Always", "Always", "Always", "Always", "Always", "Sometimes",
"Often", "Always", "Always", "Often", "Always", "Always", "Always"
)), .Names = c("DWFRSS1", "DWFRSS2", "DWFRSS3", "DWFRSS4", "DWFYSS1",
"DWFYSS2", "DWFYSS3", "DWFYSS4"), class = "data.frame", row.names = c(NA,
15L))
以下に詳述するコードを使用して、変数を再コード化しようとしています。
library(car)
cols <- c("DWFRSS1","DWFRSS2","DWFRSS3","DWFRSS4",
"DWFYSS1","DWFYSS2","DWFYSS3","DWFYSS4")
df[,cols] <- sapply(df[, cols], FUN = function(x){
recode(x, "'Never' =1; 'Rarely' =2; 'Sometimes' =3; 'Often' =4; 'Always' =5",
as.numeric.result=TRUE)})
ただし、結果のデータフレームからわかるように、「Never」がコーディングされていない場合があります。テキストからは、余分なスペース ("Never ") があるためのように見えます。再コーディング行を実行する前に、R にこれらのスペース (存在する場合) を削除させるにはどうすればよいですか?