[R] Trouble with [sv]apply

Bert Gunter gunter.berton at gene.com
Fri Apr 20 08:15:01 CEST 2012


??
Maybe:

do.call(rbind, list.of.your;matrices)

?do.call
(if you can't do it with explicit loops (i.e. for(), while()), apply
type functions are probably not what you want).

-- Bert



On Thu, Apr 19, 2012 at 2:28 PM, Worik R <worikr at gmail.com> wrote:
> 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
>
> ______________________________________________
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list