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

3 messages
Open this post in threaded view
|
Report Content as Inappropriate

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

 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
Open this post in threaded view
|
Report Content as Inappropriate

Re: How can a function in R handle different types of input?

 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