29.1.15

Calculate generalized variance using R, launched from bash or Applescript

Problem #1: How to calculate the generalized variance.  This seldom used statistic of dispersion expresses the variance in a multivariate data set.  It is calculated as the determinant of the variance-covariance matrix.

One solution: Use R.  Here is a script:

#!/usr/bin/Rscript
C<-matrix(c(49.4112,16.2815,46.4447,4.11667,54.4,-3),3,2,byrow=T)
det(cov(C))

This is a set of three latitude/longitude pairs (to help you visualize the data input structure).  Execute from a bash shell by entering the file path.


Problem #2: How to launch from Applescript.

One solution:

--1. generate R script file
set rscript to (open for access ("rscript.r") with write permission)
set eof rscript to 0

write ("#!/usr/bin/Rscript
C<-matrix(c(49.4112,16.2815,46.4447,4.11667,54.4,-3),3,2,byrow=T)
cat(det(cov(C)))
")  to rscript
close access rscript

--2. execute R script, retrieve generalized variance
do shell script ("chmod u+x /rscript.r")
set genvar to (do shell script ("/rscript.r"))
display dialog genvar

Just two very minor tricks here. First, enclose det(cov(C)) in a cat command. This will eliminate any extraneous output from R. Second, Applescript creates files with limited permissions, so you have to chmod to allow execute.