Bangyou
Bangyou

Reputation: 9816

Matrix Multiplication error in R

I would like to multiple two matrix in R using basic function %*%, for example

e <- dget(file = textConnection(
    'structure(list(u = c(4.00976069489207, 178.604060187876, 118.918710690719, 
-229.205481965294, -1.24006047251441, -95.9342713118203, 47.8278332993814, 
55.0912976611644, 4.80132026139472, -32.5090533739312, 5.42000139109041, 
512.212023076139, -1757.6162157742, 8.66354612432497, -0.379352538651801, 
111.504887168796, -266.331168788704, 2000.23693211855, -0.242980714505393, 
0.955710131117485, -5.22385427197696, -11.7346154789902, 17.6649283453744, 
9.21910124550959, -4.69614458304386), v = c(-0.0441225117765498, 
-447.707663146649, -424.574055570449, -6.39547057226855, -20.7072050928182, 
89.8052473454295, -45.1398725064628, -206.218711680996, 20.5204241988995, 
-83.8411936690584, 4.82678516352075, 16.0132244355639, -54.5879902077763, 
4.55541729541892, -0.417357418730262, 4.27524015188328, -10.6298829582797, 
89.9130220212751, 4.03963376820411, -3.90611247380684, -0.466636964249346, 
-0.583851818052153, 0.823044295174896, 0.921420474586739, -0.461728372400557
)), .Names = c("u", "v"), row.names = c(NA, -25L), class = "data.frame")'
))
norms <- apply(e, 1, function(x) sqrt(x %*% x)) # Edge lengths
v <- diag(1/norms) %*% e  

I didn't see any strange things in my data and codes, but get an error message:

Error in diag(1/norms) %*% e : 
  requires numeric/complex matrix/vector arguments

Appreciate for any suggestions to solve this problem.

Upvotes: 1

Views: 1040

Answers (1)

Roland
Roland

Reputation: 132969

e is a data.frame, see str(e). You need matrices for matrix multiplication, that's what the error is telling you.

v <- diag(1/norms) %*% as.matrix(e)  

Upvotes: 4

Related Questions