[R] Applying a function on each columns of a matrix

Carlos J. Gil Bellosta cgb at datanalytics.com
Fri Jan 29 18:18:30 CET 2010


Hello,

You could do something along the following lines:


sapply( 1:ncol( my.matrix ),
	function( i )
		my.foo( my.matrix[,i], my.parm[i]
)

Best regards,

Carlos J. Gil Bellosta
http://www.datanalytics.com


anna wrote:
> Hello everyone, I have the following matrix
>              [,1]          [,2]          [,3]         [,4]
>  [1,]  0.002809706  0.0063856960  0.0063856960  0.011749681
>  [2,]  0.004893124  0.0023118418 -0.0005122951 -0.014646465
>  [3,]  0.003547897  0.0063355297  0.0030410542  0.011403953
>  [4,]  0.004838299 -0.0040383645 -0.0090406831 -0.011027569
>  [5,]  0.035648755  0.0334815590  0.0380977404  0.059817597
> 
> I want to apply a function on each column varying the first parameter of the
> function. If I do it on one column only with apply it works perfectly as
> follow:
> apply(column1, 1, myfunction, parameter1= ..., parameter2=...)
> But when I try to do it on each column without even varying the parameter it
> doesn't work:
> apply(matrix, 2, apply, MARGIN = 1, Fun  = myfunction, parameter1 =...,
> parameter2=...)
> I get the following error:
> Error in FUN(newX[, i], ...) : 
>   unused argument(s) (2, function (X, MARGIN, FUN, ...) 
> Does someone know how to solve this? and is there a way to send a vector of
> parameter1 instead of a scalar? thank you
> 
> -----
> Anna Lippel



More information about the R-help mailing list