Useful Bits of R Code

I’m going to add bits of code that I constantly use (and constantly forget) here. Hopefully they are helpful for someone out there! (I offer no guarantees that these are correct/the best ways to go about doing these things!)

Most of these use the “data.table” package. You can install it and load it with these commands:

install.package("data.table")
library(data.table)

Creating a Median Split

d[, MedianSplitVariable := ifelse(ContinuousVariableUsedForSplit > MedianValue, 1, 0)]

Scale a Range of Predictors

This would scale all of the predictors in a dataset called “d”, in columns 2 to 34.

preds <- colnames(d[, 2:34])
d <- d[, (preds) := lapply(.SD, scale), .SDcols=preds]

Preparing Means and 95% Confidence Intervals for Plotting

This would create means and 95% confidence intervals that could then be plotted. In this example the data is in a file called “d_hits”, there are two within-subjects variables (“valence” and “concreteness”) and one between-subjects variable (“age”).

library(Rmisc)

d_hits_means <- summarySEwithin(d_hits,
measurevar = "Score",
withinvars = c("Valence", "Concreteness"),
betweenvars = "Age",
idvar = "PPT”)  

vlookup in R    

This does the equivalent of a vlookup from Excel in R

data$var <- data2[match(data$matchv, data2$matchv),]$var

Set a Reference Level for a Categorical Predictor

d <- within(d, Shape <- relevel(Shape, ref = "S”))

Label Levels of a Factor

Variable <- factor(variable, labels = c(l1 = blue, l2 = red))

ggplot Commands

Change Size of All Text

+theme(text=element_text(size=21))

Reorder Elements in an Axis by Some Column

aes(x = reorder(x1, ordercolumn), y = x2)

Center the Main Title

+ theme(plot.title = element_text(hjust = 0.5)