Tag Archives: R

R: Quickly installing and opening multiple packages

Often when doing analyses in R you need to install and load many packages, and it can be tedious to type \texttt{install.packages()} and \texttt{library()} a thousand times. The code below illustrates an efficient way of installing and opening up many packages instantly. You only need to change vector x and possibly comment out the second line of code if you have already installed the packages. Efficiency for installing packages could be improved by not reinstalling packages, but I have not checked into this yet.

#Insert packages you want to install and open in vector x
x<-c("boa","R2WinBUGS")
lapply(x,install.packages(x),character.only=T)
lapply(x,library,character.only=T)

Awkward default for the function t.test in R

I was checking the \texttt{t.test} function in R, and found out that by default it assumes unequal variances. This de facto implies that the assumption is violated, unless specified not to be the case. The main problem that this causes is that even when there is independence between groups, the test will correct for the correlation, even if it is tiny. This causes the degrees of freedom to deviate from round numbers, and might cause confusion for readers if copied directly into a paper (I have tried some things and it does not seem to affect the results).

To correct for this, the default argument \texttt{var.equal=F} should be set to true, i.e. \texttt{var.equal=T}. The code below shows the difference in degrees of freedom between the two (directly pastable into R).

#Check that t.test function is correct for Independent samples t.test for two cases
x1<-rnorm(100,5,.5);x2<-rnorm(100,6,.5);cor(x1,x2)
t1<-t.test(x1,x2,paired=F,var.equal=T,digits=6) #Beware that default is var.equal=F 
t2<-t.test(x1,x2,paired=F,var.equal=F,digits=6)
#Compare degrees of freedom between var.equal=T and var.equal=F
t1[2];t2[2]