Tim,
As Martin and Alexei pointed out, the answer is that objects of class
?data.frame? can?t do matrix operations. as.matrix() should do the trick.
Two further points:
1. When stuck on a problem like this, always check the helpfiles:
?"%*%"
Yields:
R Documentation Matrix Multiplication
Multiplies two matrices, if they are conformable. If one argument is a
vector, it will be promoted to either a row or column matrix to make the two
arguments conformable. If both are vectors it will return the inner product.
Usage
a %*% b
Arguments
a, b
numeric or complex matrices or vectors
So you here you see under arguments that only numeric or complex matrices
and vectors are "legal". As I said in section, about 95 percent of the error
you get in R result from applying a command to an object of the wrong
mode/class. Always check which mode/class is legal.
2. Another point:
To be sure, I also transposed x, using the following
for loop:
x_trans <- matrix(NA, nrow = ncol(x), ncol = nrow(x))
for(i in 1:ncol(x)){
for(j in 1:nrow(x)){
x_trans[i,j] <- x[j,i]
}
}
A less complicated way to get the transpose is t(X), which as ?"t" tells you
actually works with both matrices and data.frames.
Hope this helps,
Jens
From: gov2001-l-bounces at
lists.fas.harvard.edu
[mailto:gov2001-l-bounces at
lists.fas.harvard.edu] On Behalf Of Tim Ganser
Sent: Tuesday, February 19, 2008 11:51 PM
To: gov2001-l at
lists.fas.harvard.edu
Subject: [gov2001-l] Problem with the matrix multiplication
Dear all,
?
I am trying to write my OLS function and I am running into a problem. It'd
be great if you could take a look at what I am doing and let me know where I
am making a mistake.
?
The problem I get is the following: when I try to matrix-multiply
x_transpose with x, I get the error message: "Error in x_trans %*% x :
requires numeric matrix/vector arguments"
?
Now, examining my x, using str(), I get the following info:
'data.frame':?? 1000 obs. of? 3 variables:
?$ x1: num?? 1.171? 1.419 -0.219 -0.907? 1.212 ...
?$ x2: num? 4.68 3.08 2.14 2.22 2.62 ...
?$ x3: num? 12.8 46.5 13.5 47.0 53.1 ...
?
Examining my x_transpose, I get the following info:
?num [1:3, 1:1000]? 1.17? 4.68 12.84? 1.42? 3.08 ...
?- attr(*, "dimnames")=List of 2
? ..$ : chr [1:3] "x1" "x2" "x3"
? ..$ : NULL
By inspection, x_transpose contains all numbers.
?
To be sure, I also transposed x, using the following for loop:
x_trans <- matrix(NA, nrow = ncol(x), ncol = nrow(x))
for(i in 1:ncol(x)){
?? for(j in 1:nrow(x)){
????? x_trans[i,j] <- x[j,i]
?? }
}
Examining the result of this with str(), I get the following info:
??????? num [1:3, 1:1000]? 1.17? 4.68 12.84? 1.42? 3.08 ...
?
Again, I get the same error message when attempting matrix multiplication.
It would be great if someone could let me know what I am doing wrong as I
have been stuck on this problem for the past couple of hours and simply
can't figure it out.
?
Thanks a lot.
-Tim