Info

This file gives some examples of simple, frequently used R code. These are very beginner examples, and each section contains links for reading more. It is likely your real code will be more complicated than this!

Loading Packages

First, we usually need to load all of the packages that will be needed for the project. Below is an example of how to list all needed packages. check if the user already has them, install any that are not already installed, and load all of them.

To manually download and install a package on your own use install.packages(“package_name”) To manually load a package use library(pacakge_name)

For more on packages, see: https://psyr.djnavarro.net/packages.html

# This is a list of  packages needed
list_of_packages <- c("tidyverse", "rstatix", "readxl") 

# This checks if you have the needed libraries, and if not, installs them
new.packages <- list_of_packages[!(list_of_packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)

# This loads the packages
for(package in list_of_packages)  {
    library(package, character.only = TRUE)
}

Setting Options

Next, you might want to set some options or define some functions for later use

ADVANCED: For more on writing functions, see: https://psyr.djnavarro.net/functions.html

# for example, this options set the number of significant digits to print in output to 3, and prevent messages and warnings from being printed in the output.
options(digits=3,
        message=FALSE,
        warning=FALSE)


# for advanced users, you might want to define a function for later use. for example, Erin wrote this function to remove outliers that are more than 3 interquartile ranges away from the median. This code defines the function, which can later be called like: IQR_outliers(name_of_dataset, "name_of_variable")


IQR_outliers <- function(data, variable) {
  
  range = IQR(data[[variable]]) 
  med = median(data[[variable]])
  lower = med - 3*range
  upper = med + 3*range
  
  data <- data[data[[variable]]<upper & data[[variable]]>lower,]
  
}

Importing Data

Next, usually you need to import some data, perhaps from an excel file or other raw data source. Here we will import some fake, example data that is in .csv file format. In this example dataset, imagine there you have a 2x2 mixed design, in which each participant completes two conditions: the “rest” condition and the “wake” condition. During each condition, participants complete a memory test, and are asked how many minutes they slept the night before. There are also two experimental groups (between subjects): the “control” group and the “experimental” group.

In order for the code below to work correctly, the file you are trying to load needs to be i your CURRENT DIRECTORY in R (the folder that you see under the “Files” tab to the right). Otherwise, instead of just listing the file name, you can spell out the whole path to the file, for example: “C:/Users/EWamsley/Box/Furman Sleep Lab”.

Whenever a file won’t load correctly, it is usually because the computer can’t find it – make sure the file path is TYPED EXACTLY CORRECTLY.

In many projects, you will have more than one source of data! Here we will also import some EEG data about the participants, stored in a separate file.

For more on importing data, see: https://r4ds.hadley.nz/data-import.html

# read the example_data.csv file into a new variable called "data"
# if you have a different file format, you might need 
data <- read_csv("example_data.csv")

# view the data to make sure it looks ok
View(data)



# read the EEG.xlsx file into a new variable called "EEG"
# Because the file format is different, here we need a different function, the read_excel() function from xlread
EEG <- read_excel("EEG.xlsx")

# view the data to make sure it looks ok
View(EEG)

Joining Data

There are many ways to join two datasets together, like our “data” dataset and “EEG” datasets. Most commonly, we use what is called a “left join”, which will keep all rows in the 1st dataset, and add observations from the 2nd dataset based on some “key” that identifies which row the new observations belong in. In this case, our “data” dataset has a variable called participant_ID, which needs to match up with the column called id in the EEG dataset. This way, we will match the EEG from subject 1 up with the other data from subject 1, the EEG from subject 2 up with the other data from subject 2, and so on.

See https://r4ds.hadley.nz/joins for more on joining data.

data <- data %>% # we will start with "data" as our base dataset
  left_join(., EEG, by=join_by(participant_ID==id))# this shows to match the data from EEG into data by the participant ID variables

# in the joined data, you can see that because some participants did not have EEG data in the EEG.xlsx file, some rows for the new variables are blank, containing the notation "NA" (not applicable) 
View(data)

Cleaning and Tidying Data

Next, you will usually need several steps to clean up and organize your data. It is important that your data be “tidy”, meaning that there is one row per observation and one column per variable – this usually requires some work. In this example, we the data from the “rest” condition and the “wake” condition, listed in separate columns, but this is wrong. Instead, to make it tidy, each participant should have TWO ROWS – one containing all data from their rest condition and one containing all data from their wake condition. To convert the data into this longer (more rows and fewer columns

For real data, this is often the longest chunk of code.

See https://r4ds.hadley.nz/data-tidy#sec-pivoting for more on pivoting data to longer or wider formats.

See https://psyr.djnavarro.net/data-types.html for more about types of variables in R.

# First, lets change the variable type for a few variables. The numeric variables imported correctly, but the categorical variables imported as characters, whereas they should be "factors" (a categorical variable type).
data <- data %>%
  mutate(group = as.factor(group), # mutate group to a factor
        gender = as.factor(gender), # mutate gender to a factor
        dream_frequency = as.factor(dream_frequency)) # mutate dream frequency to a factor

#we can check the type (class) of a variable by using the "class" function, and the levels of the factor using the "levels" function
class(data$gender)
## [1] "factor"
levels(data$gender)
## [1] "female" "male"   "other"
# Next, we will "pivot" the data, so that each participant has TWO ROWS -- one containing all data from their rest condition and one containing all data from their wake condition.
data <- data %>%
  pivot_longer(., # the dot means to just use that data that we passed with the pipe character above
               c(rest_memory:wake_TST),  # the list of columns that we want to "pivot"
               names_to=c("condition", ".value"), # specifies that for each of these columns, the first part of the column name is the name of the condition, and the second part is the name of the variable
               names_sep="_") # indicates that an _ separates the condition name and variable name in each column header


# Next, let's say we want to rename the TST variable to "total_sleep" and we also want to recode the values in dream_frequency to be labeled differently. We can do both of those things at once as a part of the same "pipe"
data <- data %>%
  rename(total_sleep = TST) %>%
  mutate(dream_frequency = recode(dream_frequency, often = "high",
                                                   rarely = "medium",
                                                   never = "low"))

Exclusions

Next, you may need to exclude some datapoints. For example, here we will use filter() to exclude all observations with a low value for total_sleep. Then, we will exclude participants who do not have data for both conditions.

# filter to exclude participants with less than or equal to 450min of sleep
# the filter() function can take many different types of logical inputs. 
# to learn more about filtering: https://dplyr.tidyverse.org/reference/filter.html

data <- data %>%
  filter(total_sleep>450) 

# next, we will filter to keep only participants with both conditons, and then arrange the data by participant id

data <- data %>%
  group_by(participant_ID) %>% # groups the data by participant ID
  filter(n()==2) %>% # select only the participnts that have two rows
  ungroup() %>% # ungroup the data
  arrange(participant_ID) # arrange the data by participant ID

Descriptive Statistics

Now finally, you are ready to run analyses. First, begin with some descriptive statistics.

Below, to get means and standard deviations, we use the summarise() function. To learn more about using this powerful function, see:

https://r4ds.had.co.nz/transform.html?q=summarise#grouped-summaries-with-summarise

# SHOW NUMBER OF PARTICIPANTS PER GROUP
# first let's just look at how many participants we have left after exclusions in each group and condition, using the table() function
table(data$condition, data$group)
##       
##        control experimental
##   rest       8            7
##   wake       8            7
# GET AGE AND GENDER SUMMARY
# Because age and gender are participant-level variables, they are listed twice for each persion (once for the rest conditon and once for the wake condition). So here we will use data from only one of the two conditions to summarize age and gender (so as to not count each person twice).

# Age
# get mean and sd for age, using summarise ()
data %>% 
  filter(condition=="rest") %>% # only for the rest condition
  summarise(mean_age=mean(age), # summarize mean and standard deviation of age
            sd_age=sd(age)) 
# Gender
# because gender is a factor, we will use count() instead of summarise ()
data %>% 
  filter(condition=="rest") %>% # only for the rest condition
  count(gender)
# GET MEAN AND STANDARD DEVIATION OF MEMORY SCORE, BY CONDITION AND GROUP
# combining summarise() with the group_by() funciton allows you to get means and standard deviations for each group and condition in your data. Here we calculate and print mean and standard deviation of memory score by condition and group.
summary <- data %>% # instead of just printing the output, here we assign it to a new variable called "summary"
  group_by(condition, group) %>% # first we "group" our data frame by the relevant variables
  summarise(mean_memory = mean(memory), # then we create summary statistics 
            sd_memory = sd(memory))
## `summarise()` has grouped output by 'condition'. You can override using the
## `.groups` argument.
summary

Checking for Normality

# Before running analyses, always take a look at your main dependent variables to see if they look weird, and if they are normally distributed. If they are NOT normally distributed, you may need to transform the variables (like take the square root or log) or to use a nonparametric test.

# do these data look normally distributed?
hist(data$memory)

hist(data$total_sleep)

# we can run a test to quantitatively assess normality too. if the test IS significant, the data are NOT normally distributed
(test1 <- shapiro.test(data$memory))
## 
##  Shapiro-Wilk normality test
## 
## data:  data$memory
## W = 0.9, p-value = 0.1
(test2 <- shapiro.test(data$total_sleep))
## 
##  Shapiro-Wilk normality test
## 
## data:  data$total_sleep
## W = 1, p-value = 0.3

Statistical Analysis

Next, below are some examples of how to do t-tests, ANOVAS, and pearson’s correlations using the package ‘rstatix’. There are several difference packages you could use to do these tests, I think this one is simple and intuitive for students.

Documentation here: https://rpkgs.datanovia.com/rstatix/

# example of how to do an ANOVA with rstatix. Here we are testing the effect of both condition and group on memory score.
# the "wid" argument tells the funciton which variable indicates the participant, so it knows when two observations are from the same person
# important to use TypeIII sum of squares (type = 3)
(anova <- anova_test( data = data, 
                             dv = memory, # change in score from immediate to delayed test
                             wid = participant_ID, # identifies who is same person
                             within = condition, # within-subjects effect of condition
                             between = group, # ADHD vs control
                             type=3 ))
# example of how to do a ttest with rstatix. Here we are testing whether our two groups differ in age
# the first argument is structured like a formula, where DV ~ IV means test the effect of the IV on the DV
(ttest <- t_test( age ~ group, 
                  data = data, 
                  paired = FALSE) ) 
# NOTE: Notice that this function does not have a "wid" argument. If you do a PAIRED test you must first make sure your data are PAIRED, with two rows foe each person, and no persons with only a single row. So that the data line up correctly, data must be SORTED BUY PARTICPANT ID: https://stackoverflow.com/questions/64998984/what-does-r-assume-regarding-order-in-paired-t-test

# example of how to run a correlation test with rstatix. Here we are testing for an association between age and memory score in the rest condition
cor_test(
  data[data$condition=="rest",], # here we are looking only at the rest condition data
  vars = c(age, memory), # list variables to compare here
  method = "pearson", # if your data are NOT normally distributed, choose "spearman" instead
  use = "complete.obs" # this option will remove any rows that have missing data for one variable
)
# If your independent and dependent variables are categorical, you might want to use a chi square test. For example, let's use the chisq_test() function from rstatix to look at the relationship between gender and dream frequency.

# quickly tabluate dream recall frequency by gender with table()
table(data$gender, data$dream_frequency)
##         
##          low high medium
##   female   6    6      0
##   male     4    4      6
##   other    0    2      2
# the chi square test tells you whether dream frequency depends on gender (it doesn't)
chisq_test(data$gender, data$dream_frequency)

Visualization

Finally, let’s use the ggplot2 package to visualize some of the above comparisons.

For an introduction to ggplot2:

# visualize the effect of condition and group on memory score
ggplot(data=data, aes(x=group, y=memory, color=condition)) + # define inputs
  stat_summary(geom="pointrange", fun.data="mean_se") + # calculates and plots the mean and SE for you
  theme_classic(base_size = 20) +# make more pretty and increase font size
  labs(y="change in memory over time") # rename an axis

# visualize the difference in mean age between the two groups
ggplot(data=data, aes(x=group, y=age)) + # define inputs
  stat_summary(geom="col", fun.y="mean", fill="coral") + # plots the mean and SE for you, here we do a different "geom"
  stat_summary(geom="errorbar", fun.data= "mean_se", width=.25) + # add errorbars
  ylim(c(0,28))

# color names in R: https://r-graph-gallery.com/img/graph/42-colors-names.png


# visualize correlation between age and memory score in the rest condition
ggplot(data=data[data$condition=="rest",], aes(x=age, y=memory)) + # define inputs
  geom_point(size=3) + # here we are not creating summary statistics, just plotting each point
  geom_smooth(method="lm", size=1.5) + # add a trendline
  labs(title="correlation of age with memory") # add a title 
## `geom_smooth()` using formula = 'y ~ x'

# visualize the dream recall frequency by gender
ggplot(data=data[data$condition=="rest",], aes(x=gender, fill=dream_frequency)) + # define inputs
  geom_histogram(stat="count", position="dodge") + # plot hisograms
  labs(title="Distribution of Dream Frequency for Each Gender") + # add a title 
  theme_dark(base_size = 15) # change to dark theme and increase font size