0

110 の変数を含む調査データの大きなセットがあります。一部の回答は 1 から 5 の範囲で、1 が最良で 5 が最悪です。分析のために、5=1、4=2、3=3、2=4、1=5 を反転させたいと思います。

オブジェクトに入れると動作します:

x_inv <- recode(x, "5=1; 4=2;3=3;2=4; 1=5")

しかし、そのようにすると、オブジェクトが 110 個になってしまいます。したがって、データフレーム内でその変数を直接変更する方法を探しています。

私はちょうど再コード化しようとしました:

recode(x, "5=1; 4=2;3=3;2=4; 1=5")

その変数を見るとうまくいきますが、平均を求めると、たとえば 1.82 から 4.18 に変わっていません。

誰もそれを行う方法を知っていますか?

4

1 に答える 1

0

これは、私がそれを行う方法のより詳細な図です。

library(car) #* contains the recode function

#* Construct a sample data set
DFrame <- lapply(1:10, 
                 function(i) sample(1:5, 15, replace = TRUE))
DFrame <- as.data.frame(DFrame)
set.seed(pi)
DFrame$id = LETTERS[1:15]
DFrame <- DFrame[, c(11, 1:10)]
names(DFrame)[-1] <- paste0("Var", 1:10)

DFrame

#* Identify variables that need to be recoded.
#* Searches for any variable that has only values in 1:5
var_to_reverse <- 
  vapply(DFrame, 
         function(x) all(x %in% 1:5),
         logical(1))

#* In your case, I think recode is a bit of overkill
#* Here's how to do it with 6 - x
DFrame2 <- DFrame
DFrame2[, var_to_reverse] <- 
  lapply(DFrame2[, var_to_reverse, drop = FALSE],
         function(x) 6 - x)

#* Here's how to do it with recode, if you have a more complex situation.
DFrame3 <- DFrame
DFrame3[, var_to_reverse] <- 
  lapply(DFrame3[, var_to_reverse, drop = FALSE],
         recode, 
         recodes = "5=1; 4=2;3=3;2=4; 1=5")

#* confirm that both methods provide the same result.
identical(DFrame2, DFrame3)
于 2016-01-08T14:38:39.537 に答える