这个问题在这里已经有了答案:
How to implement coalesce efficiently in R
(8 个回答)
6年前关闭。
编辑:这是 How to implement coalesce efficiently in R 的骗局,同意。我没有意识到我的问题比我的特定应用程序更普遍,所以这个讨论很棒。
有时,随机实验中的响应变量包含在每个实验组的不同列中(下面代码中的 Y_1 到 Y_5)。通常最好将响应变量收集到单个列 (Y_all) 中。我最终按照下面的示例进行操作。但我相信有更好的方法。想法?
set.seed(343)
N <- 1000
group <- sample(1:5, N, replace=TRUE)
Y_1 <- ifelse(group==1, rbinom(sum(group==1), 1, .5), NA)
Y_2 <- ifelse(group==2, rbinom(sum(group==2), 1, .5), NA)
Y_3 <- ifelse(group==3, rbinom(sum(group==3), 1, .5), NA)
Y_4 <- ifelse(group==4, rbinom(sum(group==4), 1, .5), NA)
Y_5 <- ifelse(group==5, rbinom(sum(group==5), 1, .5), NA)
## This is the part I want to make more efficient
Y_all <- ifelse(!is.na(Y_1), Y_1,
ifelse(!is.na(Y_2), Y_2,
ifelse(!is.na(Y_3), Y_3,
ifelse(!is.na(Y_4), Y_4,
ifelse(!is.na(Y_5), Y_5,
NA)))))
table(Y_all, Y_1, exclude = NULL)
table(Y_all, Y_2, exclude = NULL)
最佳答案
我喜欢用 coalesce()
为此功能
#available from https://gist.github.com/MrFlick/10205794
coalesce<-function(...) {
x<-lapply(list(...), function(z) {if (is.factor(z)) as.character(z) else z})
m<-is.na(x[[1]])
i<-2
while(any(m) & i<=length(x)) {
if ( length(x[[i]])==length(x[[1]])) {
x[[1]][m]<-x[[i]][m]
} else if (length(x[[i]])==1) {
x[[1]][m]<-x[[i]]
} else {
stop(paste("length mismatch in argument",i," - found:", length( x[[i]] ),"expected:",length( x[[1]] ) ))
}
m<-is.na(x[[1]])
i<-i+1
}
return(x[[1]])
}
然后你可以做
Y_all <- coalesce(Y_1,Y_2,Y_3,Y_4,Y_5)
当然,这对于获取第一个非 NA 值非常特殊。
关于r - 嵌套 ifelse() 是最糟糕的;什么是最好的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30088919/