2

サンプルコードの使用:

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 にこれらのスペース (存在する場合) を削除させるにはどうすればよいですか?

4

1 に答える 1

2

あなたの価値観のいくつかは"Never "、ではなく、"Never"です。スペースはマッチングを妨げます。

たとえば、パッケージstr_trimからスペースを削除できます。stringr

アナンダが提案する完全なソリューション:

library(stringr)
as.data.frame(
  lapply(
    df, 
    function(x) 
    {
      recode(
        str_trim(x), 
        "'Never'=1; 'Rarely'=2; 'Sometimes'=3; 'Often'=4; 'Always'=5", 
        as.numeric.result = TRUE
      )
    }
  )
) 
于 2013-09-04T12:02:55.770 に答える