R Tutorial 3


You can look at correlations using cor.test(), though one note is that having missing data can mess with this command, so you might have to use “use.complete.obs=TRUE” (sidenote: for ‘True’ and ‘False’ in R you can also just use ’T’ and ‘F’). Another function is just “cor()”; this can handle more than 2 variables. Note that the cor function needs a slightly different command to tell it to drop NAs; also, it allows you to specify whether you want a regular pearson correlation, a spearman rho correlation, or kendall tau correlation.

cor.test(dataset$Cz_Gain_w2,dataset$Cz_Loss_w2, use.complete.obs=TRUE)

cor(dataset_new[2:4], use = "pairwise.complete.obs", method = "pearson")

You can also make fun correlograms to visualize correlation matrices better.

corrgram(dataset[10:15], order=TRUE, lower.panel=panel.shade,
  upper.panel=panel.pie, text.panel=panel.txt,
  main="Correlations Fun")


You can do a t-test using the t.test() command. Of note, you can make it a paired sample t-test by setting paired to True, and the t.test function does not assume equality of variances (so will give you a Welch’s t-test, unless you set var.equal to True).

t.test(RewP_Cz ~ GENDER, data = dataset, paired = FALSE,
       var.equal = TRUE)

t.test(dataset$Cz_Gain_w2,dataset$Cz_Loss_w2, paired = T,
       var.equal = TRUE)

Regression and ANCOVA

#linear regression
summary(lm(RewP_Cz ~ GENDER + AGE + SUD_comp, data = dataset))

summary(aov(RewP_Cz ~ GENDER + AGE + SUD_comp, data = dataset))

You may have noticed that you only get unstandardized parameter estimates using the “lm()” command to run a regression. This is annoying, but it’s also taught me to think about what unstandardized betas mean, and it’s actually given me a better appreciation of what effect sizes really mean by thinking about what a one unit change in the true units of X mean for unit change in Y. Anyway, to get the standardized betas easily, you can just use the “lm.beta()” command (don’t forget to load the package first though!)


#linear regression
lm.beta(lm(RewP_Cz ~ GENDER + AGE + SUD_comp, data = dataset))