簡體   English   中英

R 中的重新編碼變量返回無效

[英]Recode variables in R returns invalid

在將其轉換為數字后,我正在嘗試重新編碼此變量:

 e18$AntPT <- recode(e18$AntPT, 1 <- 0, 0 <- c(2:10))

但它返回

 Error in 1 <- 0: invalid (do_set) left-hand side to assignment

此外,最終結果應包括以下 3 部分代碼:

e18$AntPT <- as.numeric(e18$Q1501)

e18$AntPT <- recode(e18$AntPT, 1<-1, 0 <- c(2:10))



e18$AntPSDB <- as.numeric(e18$Q1505)

e18$AntPSDB <- recode(e18$AntPSDB, 10<-1, 0 <- c(2:10))



e18$AntPMDB <- as.numeric(e18$Q1502)

e18$AntPMDB <- recode(e18$AntPMDB, 100<-1, 0 <- c(2:10))

我要做的最后一件事是:

e18$Ant_Part <- (e18$AntPT + e18$AntPSDB + e18$AntPMDB)

這個總和的最終結果必須給我數字 0、1、10、11、100、101、110、111——其中一個數字給了我對最初問題的不同解釋。

如果列中有其他數字並且只想更改特定數字

-前

e18
#  AntPT AntPSDB AntPMDB
#1     1       1     100
#2     2      14       1
#3     4       2       2
#4     3      15     105
#5     1       7      24
#6     2      10       7
#7     3      11       8

現在,我們用lapply感興趣的列,並將列中的值replace為 0,它們是從 2 到 10

e18[c("AntPT", "AntPSDB", "AntPMDB")] <- lapply(e18[c("AntPT", 
  "AntPSDB", "AntPMDB")], function(x) replace(x, x %in% 2:10, 0))

以及 'AntPSDB'、'AntPMDB' (10, 100) 到 1 列中的具體數字

e18$AntPSDB[e18$AntPSDB == 10] <- 1
e18$AntPMDB[e18$AntPMDB == 100] <- 1

-后

e18
#  AntPT AntPSDB AntPMDB
#1     1       1       1
#2     0      14       1
#3     0       0       0
#4     0      15     105
#5     1       0      24
#6     0       0       0
#7     0      11       0

然后做總和

e18$Ant_Part <- (e18$AntPT + e18$AntPSDB + e18$AntPMDB)

數據

e18 <- data.frame(AntPT = c(1, 2, 4, 3, 1, 2, 3),
                   AntPSDB = c(1, 14, 2, 15, 7, 10, 11),
                   AntPMDB = c(100, 1, 2, 105, 24, 7, 8))

暫無
暫無

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

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