簡體   English   中英

用NA中的ifelse()重新編碼具有NA的變量

[英]recode variables with NAs with ifelse() in R

我將兩個二進制變量重新編碼為新變量,以便第一個變量中的任何1都在新變量中為0,第二個變量中的所有數字都保留下來。 下面的代碼顯示了我想產生的邏輯。 但是,當我運行此代碼時,使用ifelse()進行重新編碼只是重新創建x2,而沒有合並使用x1的1作為0的第一條ifelse()行。

set.seed(123)
x1 <- sample(c(0,1,NA), 20, replace = TRUE)
x2 <- sample(c(0,1,NA), 20, replace = TRUE)

recode <- ifelse(x1 == 1, 0, NA)
recode <- ifelse(x2 == 1, 1, recode)
recode <- ifelse(x2 == 0, 0, recode)

table(recode); table(x2)

謝謝

對不起,但是它確實可以滿足您的需求。 你可能已經忘記了的問題是,與任何NA的比較的結果也NA,所以ifelse( x2 == 0, yes, no )返回NA(而不是no ),如果x2 == NA

更好地嘗試

recode <- rep( NA, length( x1 ) )
recode[ x1 == 1 ] <- 0
recode[ ! is.na( x2 ) ] <- x2[ ! is.na( x2 ) ]

也許你想要這個?

ifelse(is.na(x2), ifelse(x1 == 1, 0, NA), x2)

您重寫了這些結果。 help('ifelse')頁面的Details部分中的相關行是:

 Missing values in test give missing values in the result.

recode <- ifelse(x1 == 1, 0, NA)
recode[ !is.na(x2)] <- x2[!is.na(x2)]

我發布此消息只是為了弄清楚是否有人出於某種原因不建議使用這種襯板:

recode <- ifelse(x1 %in% 1 & is.na(x2), 0, x2)

暫無
暫無

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

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