[R] apply() and unary operators

Thomas Lumley tlumley at u.washington.edu
Thu Mar 13 05:16:48 CET 2003


On Thu, 13 Mar 2003, Robin Hankin wrote:

> Hi everyone.
>
> What's going on here?
>
>
> > a <- matrix(1:4,2,2)
> > a
>      [,1] [,2]
> [1,]    1    3
> [2,]    2    4
> > apply(a,2,sum)
> [1] 3 7
> > apply(a,2,"+")
>      [,1] [,2]
> [1,]    1    3
> [2,]    2    4
> > apply(a,1,"+")
>      [,1] [,2]
> [1,]    1    2
> [2,]    3    4
> >
>
> help(apply) says that "+" should be quoted but is otherwise silent on
> unary operators.  I don't understand apply() here at all.
>

The problem is that "+" takes two arguments, but apply() gives it a single
vector argument.  I think you are actually getting the unary "+" function,
so  apply(a,1,"+") applies unary "+" to each row (which has no effect) and
then sticks the results together into a matrix.

	-thomas



More information about the R-help mailing list