Re: [R] Apply a function to columns of a matrix

2012-09-08 Thread arun
Hi, You can also use sapply() sapply(split(t(a),1:ncol(a)),function(x) sum(diff(b)*(x[-1]+x[-length(x)]))/2) #   1    2    3    4    5    6    7    8    9   10   #99  279  459  639  819  999 1179 1359 1539 1719 A.K. - Original Message - From: Andras Farkas To: "r-help@r-project.org"

Re: [R] Apply a function to columns of a matrix

2012-09-08 Thread arun
Hi, Sorry, there was a mistake in my previous code: f1<-function(x) sum(diff(b)*(x[-1]+x[-length(x)]))/2 a1<-split(t(a),1:ncol(a)) mapply(f1,a1) #   1    2    3    4    5    6    7    8    9   10   #99  279  459  639  819  999 1179 1359 1539 1719 A.K. - Original Message - From: Andras

Re: [R] Apply a function to columns of a matrix

2012-09-08 Thread jim holtman
Is this what you wanted? You had two arguments to your function, but only supplying one via the 'apply'. Also your argument names were the same as your variables which was confusing. > a <-matrix(c(1:100),ncol=10) > b <-matrix(c(2,4,6,8,10,12,14,16,18,20)) > > apply(a,2,function(y,x) sum(diff(x)