[R] Multi-dimensional function.

Wolfgang Huber huber at ebi.ac.uk
Fri Jan 4 23:59:38 CET 2008


José Luis Aznarte M. ha scritto:
>     Hi there! Happy new year to everyone!
>     There's a piece of code that I must write that's driving me crazy. 
> Maybe any of you has previous experiences in something similar. Any help 
> will be greatly appreciated!
> 
>     The problem is as follows. I have a matrix Z with dimensions c(m, 
> p). I have two vectors
> Gamma and Th with length p.
>     What I want to do is, for j in 1:p, for each pair (Gamma[j], Th[j]), 
> apply the logistic function to each column of z, using plogis(Z[,j], 
> Th[j], 1/Gamma[j]). Then, by concatenating the result of each iteration 
> I would obtain a matrix lZ with dimensions c(m, p).
> 
>     Now, the question is: is there a neat way to do this in a single 
> step, i.e., without the obvious loop? I have a not-so-good relationship 
> with the "apply" family, but I suspect there should be a way. Sorry if 
> this is a silly question...
>     Thanks and best wishes for the new year to you all! Salud!
> 

Dear Jose,

I think something similar to

   lZ = lapply(seq_len(ncol(Z)), function(i) Z[,i])

   mapply(plogis, lZ, Th, 1/Gamma)

should do the trick. But I doubt it will lead to better performance, my 
understanding is that the for-loop would be more efficient in terms of 
CPU-load and memory.

  Best wishes
	Wolfgang




More information about the R-help mailing list