[英]New column with mutate and ifelse but keep NAs in R
I have a simple question but it is giving me a hard time.我有一个简单的问题,但这让我很难过。
I wish to recode a varibale with a ifelse function but I want to keep the NAs (in the variable "party") as NAs.我希望用 ifelse function 重新编码一个变量,但我想将 NA(在变量“party”中)保留为 NA。
This is what I am doing.这就是我正在做的事情。 I have a variable with vote choice ("party") and I want to recode a new variable ("RRP") if participants choose a specific set of parties:我有一个带有投票选择的变量(“派对”),如果参与者选择一组特定的派对,我想重新编码一个新变量(“RRP”):
df<- df %>%
mutate(RRP = if_else(party %in% c("4",#SPP/UDC
"12",#Swiss Democrats
"13",#FDU
"14", #PSL
"15"), 1, 0))
The problem is that participants who have NAs in the "party" variable are now being recoded as 0 because they don't fullfil the condition in ifelse.问题是在“party”变量中有 NA 的参与者现在被重新编码为 0,因为他们没有满足 ifelse 中的条件。
I also tried this:我也试过这个:
df<- df %>%
mutate(RRP = if_else(party %in% c("4",#SPP/UDC
"12",#Swiss Democrats
"13",#FDU
"14", #PSL
"15"), 1, 0, na.rm=TRUE))
but it just yield an error.但它只会产生一个错误。
Do you have any other ideas?你还有其他建议吗?
Thanks a lot!非常感谢!
%in%
returns FALSE
for NA
value and not NA
. %in%
为NA
值返回FALSE
而不是NA
。 So when use it in ifelse
/ if_else
it executes the FALSE
condition in them.因此,当在ifelse
/ if_else
中使用它时,它会在其中执行FALSE
条件。 We can use case_when
here:我们可以在这里使用case_when
:
library(dplyr)
df %>%
mutate(RRP = case_when(party %in% c(4, 12:15) ~ 1,
is.na(party) ~ NA_real_,
TRUE ~ 0))
# party RRP
#1 13 1
#2 14 1
#3 15 1
#4 16 0
#5 17 0
#6 NA NA
data数据
df <- data.frame(party = c(13:17, NA))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.