In the function call in 'apply', you are passed the values in the rows:
> set.seed(30)
> z = matrix(rnorm(10), 5, 2)
> apply(z, 1, function(x) sum(z[x,1]*1, z[x,2]*3))
[1] -0.908321 0.000000 0.000000 -5.822442 -5.822442> z
[,1] [,2]
[1,] -1.2885182 -1.5113079
[2,] -0.3476894 0.1105080
[3,] -0.5216288 -0.7607962
[4,] 1.2734732 -0.6698970
[5,] 1.8245206 0.2745197> sum(z[1,1]*1,
+ z[1,2]*3)
[1] -5.822442> # correct use of apply
> apply(z, 1, function(x) x[1]*1 + x[2]*3)
[1] -5.82244202 -0.01616527 -2.80401753 -0.73621789
2.64807967>
On Tue, Apr 28, 2009 at 9:02 PM, megh <megh700004@yahoo.com> wrote:
>
> Hi all, can you please clarify me what is the wrong with following codes :
>
> set.seed(30)
> z = matrix(rnorm(10), 5, 2)
> apply(z, 1, function(x) sum(z[x,1]*1, z[x,2]*3))
>
> However I can not get the desired result. For example, "sum(z[1,1]*1,
> z[1,2]*3)" gives -5.822442 which is actually correct. Am I missing
> something
> in apply() function?
>
> Regards,
>
>
> --
> View this message in context:
> http://www.nabble.com/Help-on-apply%28%29-function-tp23288839p23288839.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
>
http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
[[alternative HTML version deleted]]