简体   繁体   中英

R error | Vectors calculations returns the wrong matrix size | Non-conformable arrays

I am trying to calculate Within And Total Sum of Squares and Cross-Product Matrices (W) in one-way MANOVA. I have a treatment matrix tm :

 n x1 x2
 1  6 7
 1  5 9
 1  8 6
 ...
 2  3 3
 2  1 6
 2  2 3
 ...
 3  2 3
 3  2 3
 3  5 1
 ...

I also have each individual observations in their own variables, for example:

 x111 = x[1,1]
 x112 = x[2,1]
 ...

that are also in the variables that create vectors:

# creating vectors

t11 = c(x111, x111_2) # 6,7
t12 = c(x112, x112_2) # 5,9 
t13 = c(x113, x113_2) # 8,6
t14 = c(x114, x114_2) # 4,9
t15 = c(x115, x115_2) # 7,9
t21 = c(x211, x211_2) # 3,3
t22 = c(x212, x212_2) # 1,6
t23 = c(x213, x213_2) # 2,3
t31 = c(x311, x311_2) # 2,3
t32 = c(x312, x312_2) # 5,1
t33 = c(x313, x313_2) # 3,1
t34 = c(x314, x314_2) # 2,3

>dput(t11)
c(6,7)

I am trying to calculate W (Within And Total Sum of Squares and Cross-Product Matrices).

The means are

> x1 # treatment 1
[1] 6 8

> x2  # treatment 2
[1] 2 4

> x3  # treatment 3

[1] 3 2

> x # overall mean

     X1 X2
[1,]  4  5

The code I have is:

W = (t(t11)-t(x1))*(t11-x1)
+(t(t12)-t(x1))%*%(t12-x1)
+(t(t13)-t(x1))%*%(t13-x1)
+(t(t14)-t(x1))%*%(t14-x1)
+(t(t15)-t(x1))%*%(t15-x1)
+(t(t21)-t(x2))%*%(t21-x2)
+(t(t22)-t(x2))%*%(t22-x2)
+(t(t23)-t(x2))%*%(t23-x2)
+(t(t31)-t(x3))%*%(t31-x3)
+(t(t32)-t(x3))%*%(t32-x3)
+(t(t33)-t(x3))%*%(t33-x3)
+(t(t34)-t(x3))%*%(t34-x3)

The result I get is:

Error in (t(t11) - t(x1)) * (t11 - x1) + (t(t12) - t(x1)) %*%  : 
non-conformable arrays

When I isolated each statements, I got this:

> (t(t11)-t(x1))%*%(t11-x1)
      [,1]
 [1,]   1
> (t(t12)-t(x1))%*%(t12-x1)
     [,1]
[1,]    2

Why do these statements evaluate to 1x1 matrices? When I calculate 2x1 and 1x2 operations (subtraction and multiplication) manually, I get 2x2 for both. Here is an online calculator

It can be confusing sometimes when working with vectors in R and you want to do matrix multiplication. A vector in R (say, x = c(1,2) ) is printed like it might be a row vector, but R treats it as a column vector.

With that in mind, to get the 2x2 matrix you want, do

t11 = c(6, 7)
x1 = c(6, 8)
(t11 - x1) %*% t(t11 - x1)

No need for too many transposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM