[R] How can a function in R handle different types of input?

Rui Barradas ruipbarradas at sapo.pt
Wed May 2 18:36:09 CEST 2012


Hello,


stella wrote
> 
> Hi,
>  
> How can a function in R handle different types of input?
> I have written a function, which should calculate the slope from several
> 3-time-point measurements by linear regression 
> 
> 4 three-time-point-measurements:
> x<-cbind(c(1,2,3,4),c(2,3,4,5),c(3,4,5,6))
> 
> time points:
> time<-c(1,3,9)
> 
> function for calculating the slope by linear regression:
> fit<-function(xx,t){slope <- coefficients(lm(log(xx) ~ 0 + t))[1]
> return(slope)
> }
> alpha<-fit(x[1,],time)
>  
> At the moment the function output 'alpha' is calculated for
> x(x1=1,x2=2,x3=3). I would like to get 'alphas' for all four rows of x
> without using a for-loop.  If I use 'mapply', I get outputs to very entry
> of x (12 outputs) instead of four.
>  
> Thank you very much in advance! Yor help is really appreciated!
> Stella
> 

It's close to what you were doing, just try

apply(x, 1, fit, time)

Hope this helps,

Rui Barradas


--
View this message in context: http://r.789695.n4.nabble.com/How-can-a-function-in-R-handle-different-types-of-input-tp4603263p4603754.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list