Re: [S] tapply: problem, solution, question

John Wallace (jrw@fish.washington.edu)
Thu, 30 Apr 1998 00:44:52 -0700 (PDT)


Here is one way, as I (and others) have pointed out in the past:

resp1_rnorm(20)
resp2_rnorm(20)
stim_c(rep(1,10), rep(2,10))
tapply(1:length(resp1), stim, function(x) cor(resp1[x], resp2[x]))

1 2
-0.1527429 0.2334725

--------------------------------------

>From jrw@fish.washington.eduThu Apr 30 00:39:07 1998
Date: Mon, 7 Nov 1994 10:54:24 -0800 (PST)
From: John Wallace <jrw@fish.washington.edu>
To: S-news <s-news@utstat.toronto.edu>
Subject: Back to tapply; a trick

If you want to stick with tapply(), but want to go beyond the restriction
of the 'data to be grouped by the indices' as only a VECTOR then the
following will work.

Use '1:nrow(x)' as the vector and write a function which uses what tapply
passes through as elements to '[]'.

An example, find the determinant of the 3 2X2 matrices in the first two
columns of x, x[,3] being the index;

S>x

[,1] [,2] [,3]
[1,] 1 4 1
[2,] 2 3 1
[3,] 1 5 2
[4,] 4 7 2
[5,] 5 8 3
[6,] 6 5 3

tapply(1:nrow(x),x[,3],function(i) prod(eigen(x[i,-3])$values))
1 2 3
-5 -13 -23

So for example the first pass is;

prod(eigen(x[c(1,2),-3])$values)

which is -5.

-jrw

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news