[R] Trouble with [sv]apply
Worik R
worikr at gmail.com
Thu Apr 19 23:28:21 CEST 2012
Friends
I clearly donot understand how sapply and vapply work.
What I have is a function that returns a matrix with an indeterminate
number of rows (some times zero) but a constant number of columns. I
cannot reliably use an apply function to assemble the matrices into a
matrix. I am not sure it is possible.
I can demonstrate the core of my confusion with this simple code.
A.f <- function(i){
ret <- matrix("a", i, 7)
cat(i, class(ret), dim(ret), "\n")
return(ret)
}
V.f <- function(){
SS <- vapply(c(1,2),
A.f,
rep('a', 7))
return(SS)
}
S.f <- function(){
SS <- sapply(c(1,2),
A.f)
cat("SS", class(SS), dim(SS), "\n")
return(SS)
}
Calling V.f() fails:
> V.f()
1 matrix 1 7
2 matrix 2 7
Error in vapply(c(1, 2), A.f, rep("a", 7)) :
values must be length 7,
but FUN(X[[2]]) result is length 14
>
Calling S.f() returns a list.
Do I have to accept I am going to be getting a list and I have to
assemble a matrix in a loop?
cheers
Worik
More information about the R-help
mailing list