Message-ID: <971536df05042916241ad51a73@mail.gmail.com>
Date: 2005-04-29T23:24:08Z
From: Gabor Grothendieck
Subject: generalized matrix product ?
In-Reply-To: <OFC925A926.D0B12E17-ON87256FF2.00621F9D-87256FF2.00651B58@blm.gov>
On 4/29/05, George_Heine at blm.gov <George_Heine at blm.gov> wrote:
>
>
> Is there available in R a generalized inner product or matrix product,
> similar to 'outer(x,y, fun)', where one can specifiy an arbitrary function
> in place of ordinary multiplication?
>
> Here's my application. I frequently analyze user questionnaires from our
> HR/training department. These have questions of the form
> "please rate your skill in task X",
> and other questions of the form
> "Have you taken course Y?" (or "How many years since you have taken
> course Y?")
>
> I look at rank correlation between the (suitably ordered) vectors of
> responses to a question in the first group and a question in the second
> group. (The two vectors have the same length, but I want to replace the
> standard inner product with a different operation; in this case, rank
> correlation) Repeat the process across all possible pairs of questions.
>
> Is there a way to accomplish this without nested 'for' statements?
Try this:
inner <- function(a,b,f, ...) {
f <- match.fun(f)
apply(b,2,function(x)apply(a,1,function(y)f(x,y, ...)))
}
data(iris); irish <- head(iris)[,-5] # test data
res <- inner(t(irish), irish, cor, method = "spearman") # test
res2 <- cor(irish, method = "spearman") # should give same result
identical(res, res2) # TRUE