r - how to generate a linear regression matrix like cor() -
i have dataframe below :
a1 a2 a3 a4 1 3 3 5 5 2 4 3 5 5 3 5 4 6 5 4 6 5 7 3
i want linear regression every 2 columns in dataframe, , set intercept
0.
in other words, want coefficients of lm(a1~a2+0), lm(a1~a3+0), lm(a1~a4+0), lm(a2~a1+0), lm(a2~a3+0)...
in cor()
, if input dataframe, matrix back, e.g. below,
a1 a2 a3 a4 a1 1.0000000 0.9467293 0.8944272 0.2045983 a2 0.9467293 1.0000000 0.9622504 0.4989222 a3 0.8944272 0.9622504 1.0000000 0.4574957 a4 0.2045983 0.4989222 0.4574957 1.0000000
in lm()
there way same kind of matrix?
thanks.
here's pretty general strategy
dd<-read.table(text="a1 a2 a3 a4 1 3 3 5 5 2 4 3 5 5 3 5 4 6 5 4 6 5 7 3", header=t) mm<-diag(ncol(dd)) mm[lower.tri(mm)] <- combn(dd, 2, function(x) coef(lm(x[,2]~x[,1]+0))) mm[upper.tri(mm)] <- rev(combn(dd[length(dd):1], 2, function(x) coef(lm(x[,2]~x[,1]+0))))
this gives matrix
mm # [,1] [,2] [,3] [,4] # [1,] 1.0000000 1.202381 0.7738095 0.9285714 # [2,] 0.8255814 1.000000 0.6592593 0.7925926 # [3,] 1.2441860 1.508475 1.0000000 1.2033898 # [4,] 0.9069767 1.101695 0.7481481 1.0000000
where element [4,1] same coef(lm(a4~a1+0, dd))
, element [2,3] same coef(lm(a2~a3+0, dd))
Comments
Post a Comment