Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Compare all columns in a matrix against each in loop

I have a matrix of variables and I am trying to run a loop that compares the difference between all of the variables in a regression such that a matrix is produced and filled in with the difference. Below is some simulation code to get at the problem. I would like to produce a matrix that compares x_1, x_2, and x_3 to produce a 3x3 matrix that is symmetric about the diagonal, which should all be zeros.

y <- sample(seq(1:4), 100, replace = TRUE)
x_1 <- sample(seq(1:2), 100, replace = TRUE)
x_2 <- sample(seq(1:4), 100, replace = TRUE)
x_3 <- sample(seq(1:4), 100, replace = TRUE)

frame <- cbind(x_1, x_2, x_3)
dif <- matrix(NA, ncol = 3, nrow = 3)

for(i in 1:3){
    model_1 <- lm(y ~ frame[,i])
    model_2 <- lm(y ~ frame[,i])
    dif[i]<- (model_2$coef[2] - model_1$coef[2])
}

I'm confused on how to index the loop and refer to the matrix of x's to produce a 3x3 table with the results - any help would be much appreciated.

like image 978
coding_heart Avatar asked Jan 30 '26 16:01

coding_heart


1 Answers

 vcoef <- numeric(3)
 for(i in 1:3) { 
     vcoef[i] <- coef( lm(y~frame[,i]))[2]
               }

outer(vcoef, vcoef, "-")
#----------
          [,1]        [,2]        [,3]
[1,] 0.0000000 -0.15208933 -0.17302592
[2,] 0.1520893  0.00000000 -0.02093659
[3,] 0.1730259  0.02093659  0.00000000

If you didn't want the redundant information you could get all the pairwise differences with combn:

> combcos  <- combn(vcoef,2)
> combcos[1, ] -combcos[2, ]
[1] -0.15208933 -0.17302592 -0.02093659
like image 152
IRTFM Avatar answered Feb 02 '26 11:02

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!