Hello again, Let say I have following user defined function: fn <- function(x, y) { Vec1 <- letters[1:6] Vec2 <- 1:5 return(list(ifelse(x > 0, Vec1, NA), ifelse(y > 0, Vec2, NA))) } Now I have following calculation:> fn(-3, -3)[[1]] [1] NA [[2]] [1] NA> fn(3, -3)[[1]] [1] "a" [[2]] [1] NA Here I can not understand why in the second case, I get only the first element "a" of the corresponding vector 'Vec1'? I want to get complete vector(s) as the function return. Can somebody help me how to achieve that? Thanks and regards,
Hello, You get only one value because ifelse is vectorized, and the condition has length(x > 0) == 1. (You get as many values as there are in the condition.) Try instead fn2 <- function(x, y) { Vec1 <- letters[1:6] Vec2 <- 1:5 list(if(x > 0) Vec1 else NA, if(y > 0) Vec2 else NA) } fn2(-3, -3) fn2(3, -3) Hope this helps, Rui Barradas Em 22-03-2013 18:43, Christofer Bogaso escreveu:> Hello again, > > Let say I have following user defined function: > > fn <- function(x, y) { > Vec1 <- letters[1:6] > Vec2 <- 1:5 > return(list(ifelse(x > 0, Vec1, NA), ifelse(y > 0, Vec2, NA))) > } > > Now I have following calculation: > >> fn(-3, -3) > [[1]] > [1] NA > > [[2]] > [1] NA > >> fn(3, -3) > [[1]] > [1] "a" > > [[2]] > [1] NA > > > Here I can not understand why in the second case, I get only the first > element "a" of the corresponding vector 'Vec1'? I want to get complete > vector(s) as the function return. > > Can somebody help me how to achieve that? > > Thanks and regards, > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
On 2013-03-22 11:43, Christofer Bogaso wrote:> Hello again, > > Let say I have following user defined function: > > fn <- function(x, y) { > Vec1 <- letters[1:6] > Vec2 <- 1:5 > return(list(ifelse(x > 0, Vec1, NA), ifelse(y > 0, Vec2, NA))) > } > > Now I have following calculation: > >> fn(-3, -3) > [[1]] > [1] NA > > [[2]] > [1] NA > >> fn(3, -3) > [[1]] > [1] "a" > > [[2]] > [1] NA > > > Here I can not understand why in the second case, I get only the first > element "a" of the corresponding vector 'Vec1'? I want to get complete > vector(s) as the function return. > > Can somebody help me how to achieve that?From help(ifelse): "ifelse returns a value with the same shape as test" i.e. in your case, the same 'shape' as 'x > 0', a single value. You _could_ make ifelse() work with, e.g., ifelse(rep(x, 6) > 0, ....) but you probably want if() instead. Peter Ehlers