我有一大堆包含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。
有谁知道怎么做?
答案 0 :(得分: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)