statistics - Efficient Method to do Calculations on Joint Distributions in R -
statistics - Efficient Method to do Calculations on Joint Distributions in R -
if have next joint distribution top row value of y , first column on left values of x, efficient/clean way of going calculating covariance , correlation between x , y?
i thinking of loading each row new variable , doing necessary calculations , running cov() , cor() functions, know there has improve way?
thanks!
| | 14 | 22 | 30 | 40 | 65 | |---|-----|-----|-----|-----|-----| | 1 | .02 | .05 | .10 | .03 | .01 | | 5 | .17 | .15 | .05 | .02 | .01 | | 8 | .02 | .03 | .15 | .10 | .09 |
you should utilize matrix multiplication results. next not most efficient way, uses formulas in straightforward way.
# input info yvec <- c(14, 22, 30, 40, 65) xvec <- c(1, 5, 8) jp <- matrix(c(.02, .05, .10, .03, .01, .17, .15, .05, .02, .01, .02, .03, .15, .10, .09), nrow=length(xvec), ncol=length(yvec), true) ex <- rowsums(jp) %*% xvec ## e(x) ex2 <- rowsums(jp) %*% xvec^2 ## e(x^2) vx <- ex2 - (ex)^2 ## var(x) ey <- colsums(jp) %*% yvec ## e(y) ey2 <- colsums(jp) %*% yvec^2 ## e(y^2) vy <- ey2 - (ey)^2 ## var(y) exy <- xvec %*% jp %*% yvec ## e(xy) (cxy <- exy - ex*ey) ## covariance (rxy <- cxy /sqrt(vx * vy)) ## correlation
r statistics distribution covariance correlation
Comments
Post a Comment