ifelse
does exactly what you want:
> ifelse(is.na(x[,2]), x[,1], x[,2])
[1] 12 25
If speed is paramount (and you don't want to mess with C), you can try:
y <- x[,2]
y[is.na(y)] <- x[is.na(y), 1]
This effectively shortcircuits some of the overhead of ifelse
. Consider:
set.seed(1)
x <- cbind(sample(1:1e5), sample(c(1:95000, rep(NA, 5000))))
library(microbenchmark)
microbenchmark(
z <- ifelse(is.na(x[,2]), x[,1], x[,2]),
{y <- x[,2]; y[is.na(y)] <- x[is.na(y), 1]},
times=10
)
# Unit: milliseconds
# expr min median
# z <- ifelse(is.na(x[, 2]), x[, 1], x[, 2]) 30.46 33.06
# y <- x[, 2]; y[is.na(y)] <- x[is.na(y), 1] 5.48 5.77
identical(y, z)
# [1] TRUE