【问题标题】:recode into same variable重新编码到同一个变量
【发布时间】:2016-01-08 14:05:29
【问题描述】:

我有一组包含 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。

有人知道怎么做吗?

【问题讨论】:

  • 如果值是数字,为什么不直接使用6 - x
  • 谢谢!但是我必须对数据集中的所有观察结果都这样做。 R中是否有可能只是将一个变量重新编码为同一个变量?
  • 只要data$answer &lt;- (6 - data$answer)
  • 6 - x # 返回一个向量,每个元素都从 6 中减去,还要注意:6 - mean(x) 与 mean(6 - x) 相同
  • recode 函数是什么?

标签: r variables transform recode


【解决方案1】:

这里有一个更详细的说明我将如何做到这一点。

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)

【讨论】:

  • 完美!谢谢 :-) 我使用了重新编码的,它有效!
猜你喜欢
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多