0

Consider for code given :

ne<-rep(1,n)
meanx <- drop(one %*% x)/n

then there is an error reported

is the vector able to %*%matrix or data.frame ?

is this only caused by version of R?

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
suemi
  • 69
  • 5
  • 6
    Please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). What is `n`? What is `one`? What is `x`? – Thomas Aug 05 '13 at 14:28

2 Answers2

1

If you meant

n <- 100
one<-rep(1,n)
meanx <- drop(one %*% one)/n    ,

then it works like a charm...

Doctor Dan
  • 771
  • 4
  • 11
  • yeah,I mean that. But I can not uderstand how it works like a charm,what does it mean? I am a chinese,not familiar with some english saying. – suemi Aug 07 '13 at 04:37
  • "it works like a charm" means "it works well." I think Doctor Dan is saying that he's not clear what you are asking because your code worked for him with the sample data he generated. It would be useful to us if you provided sample data with your question. @Doctor_Dan, I believe `x` is supposed to be a dataframe. – David Marx Aug 07 '13 at 05:51
1

The %*% operator won't work on a dataframe, but if you cast the data.frame to a matrix it will work.

X = rnorm(100)
Y = rnorm(100)
df = data.frame(X,Y)
M = as.matrix(cbind(X,Y))

# this works fine
X %*% M 

            X        Y
[1,] 99.95776 3.955938

# This one throws an error. But it can be fixed!
X %*% df    

Error in X %*% df : requires numeric/complex matrix/vector arguments

# Ta da!
X %*% as.matrix(df)

            X        Y
[1,] 99.95776 3.955938
David Marx
  • 8,172
  • 3
  • 45
  • 66
  • Thank you for your help. Then is there a method for dataframe to do such thing like %*% easily? Casting the data.frame to a matrix every time is disgusting. – suemi Aug 07 '13 at 04:40
  • is casting really that bad? If it's the same dataframe each time, you could just cast it once by storing the result in a variable. Otherwise, my only other thought is to use apply which would get uglier, or homebrew your own function, like `MatrixMultiply <- function(X,Y){as.matrix(X) %*% as.matrix(Y)}`. You're still casting to a matrix each time so this is really just an aesthetic difference. – David Marx Aug 07 '13 at 05:56