I've encountered an issue wrapping nested sapply pasting code into ifelse() that checks to see that all the components are non-NA. The sapplys work great when they aren't in the ifelse()... Why is this?
Given some parameters:
a = c(1, 2, 3)
b = c("a", "b")
c = c("X", "Y")
Here's how I've managed to paste together all the combinations
as.vector(sapply(sapply(a, function(x){paste(x, b, sep = "")}),
function(x){paste(x, c, sep = "")}))
The output is this. It's exactly what I want:
[1] "1aX" "1aY" "1bX" "1bY" "2aX" "2aY" "2bX" "2bY" "3aX" "3aY" "3bX" "3bY"
However, if I put the exact same code in an ifelse() that checks to make sure the parameters aren't NA, the output is different.
ifelse(!is.na(a) & !is.na(b) & !is.na(c),
as.vector(sapply(sapply(a, function(x){paste(x, b, sep = "")}),
function(x){paste(x, c, sep = "")})), "Error")
[1] "1aX" "1aY" "1bX"
Warning messages:
1: In !is.na(a) & !is.na(b) :
longer object length is not a multiple of shorter object length
2: In !is.na(a) & !is.na(b) & !is.na(c) :
longer object length is not a multiple of shorter object length
Why? It's obvious that a, b, and c are different lengths; I don't see why that matters in an ifelse(). To clarify, the !is.na() is checking to see if the whole vector is NA, NOT for things like c(1, NA, 3) because I'll be using the code in a context where that won't ever happen. I'm doing this because the ifelse's are part of larger function where the parameters default to NA; certain combinations of non-NA parameters require a certain actions. For example, if b = NA, then the code above should produce an ERROR. How can I accomplish both the nested pasting AND the conditional checking?