簡體   English   中英

重新編碼為相同的變量

[英]recode into same variable

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

有誰知道這是怎么做到的嗎?

這是我將如何做的更詳細的說明。

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM