This is an R Markdown Notebook. When you execute code within the notebook, the results appear beneath the code. Try executing this chunk by clicking the Run button within the chunk or by placing your cursor inside it and pressing Ctrl+Shift+Enter. Add a new chunk by clicking the Insert Chunk button on the toolbar or by pressing Ctrl+Alt+I.

This file gives some examples of simple, frequently used R code.

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)

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

# 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)
  
}

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

# for example, this option sets the number of significant digits to print in output:
options(digits=2)


# for advanced users, you might want to define a function for later use. for example, Erin wrote this function 

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.

# read the .csv file into a new variable called "data"
# if you have a differernt file format, you might need a different function, such as the read_excel() function from xlread
data <- read_csv("example_data.csv")
## Rows: 20 Columns: 9
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): group, gender, dream_frequency
## dbl (6): participant_ID, age, rest_memory, wake_memory, rest_TST, wake_TST
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# view the data to make sure it looks ok
View(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.

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

# 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"

data <- data %>%
  mutate(group = as.factor(group)) %>%
  mutate(gender = as.factor(gender)) %>%
  mutate(dream_frequency = as.factor(dream_frequency))


# 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"))

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

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

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

# because age is a participant-level variable, here we will use data from only one of the two conditions (so as to not count each person twice)
(mean_age = mean(data[data$condition=="wake",]$age)) # calculate and print mean age
## [1] 22
# because gender is a participant-level variable, here we will use data from only one of the two conditions (so as to not count each person twice)
table(data[data$condition=="wake",]$gender, data[data$condition=="wake",]$group) # make a quick table showing gender distribution by group
##         
##          control experimental
##   female       4            4
##   male         6            3
##   other        0            2
# calculate and print mean and standard deviation of memory score by condition and group
summary <- data %>%
  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

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
(ttest <- t_test( age ~ group, # this first argument is structured like a formula, where DV ~ IV means test the effect of the IV on the DV
                  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 
)

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

# visualize the effect of both condition and group on mean 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))
## Warning: The `fun.y` argument of `stat_summary()` is deprecated as of ggplot2 3.3.0.
## ℹ Please use the `fun` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

# 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 
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `geom_smooth()` using formula = 'y ~ x'