NDL R Tutorial

Ryan Mears
March 24, 2014

Overview

Working with data in R with the RStudio GUI

  • Get and Shape data into tidy arrangements
  • Analyze and Summarize data with R packages
  • Explore and Present with data visualization and publication quality tables and plots

Installing R and RStudio

R

Install R

The R Foundation for Statistical Computing

RStudio

Install RStudio

RStudio

Get and Shape Data

Reading Data and Code

  • read.csv()
getwd()
[1] "/Users/R/Downloads/doesmindmatter-NeuralDynamics-RTutorial-2e56d2d"
  • source()
getwd()
[1] "/Users/R/Downloads/doesmindmatter-NeuralDynamics-RTutorial-2e56d2d"

Data and Code in R

Create variables

  • c()
hc_subjs <- c('sbj101','sbj102','sbj105')
sz_subjs <- c('sbj103','sbj104','sbj106')
  • seq()
    • seq_len(6)
      1, 2, 3, 4, 5, 6
    • seq(from = -2, to = 3, by = 1)
      -2, -1, 0, 1, 2, 3
  • rep()
    • rep(c('HC','SZ'), times = 1, each = 3)
      HC, HC, HC, SZ, SZ, SZ
    • rep(c('HC','SZ'), times = 3, each = 1)
      HC, SZ, HC, SZ, HC, SZ

Create variables

x <- seq_len(6)
subjs <- c(hc_subjs,sz_subjs)
cbind(x,subjs)
     x   subjs   
[1,] "1" "sbj101"
[2,] "2" "sbj102"
[3,] "3" "sbj105"
[4,] "4" "sbj103"
[5,] "5" "sbj104"
[6,] "6" "sbj106"

Create variables

  • cbind()
  hc_2 <- cbind(hc_subjs,"hc")
  sz_2 <- cbind(sz_subjs,"sz")
  sz_2
     sz_subjs     
[1,] "sbj103" "sz"
[2,] "sbj104" "sz"
[3,] "sbj106" "sz"
  • rbind()
 grp_subjs <- rbind(hc_2,sz_2)
  colnames(grp_subjs)<-c("subj","group")
  grp_subjs
     subj     group
[1,] "sbj101" "hc" 
[2,] "sbj102" "hc" 
[3,] "sbj105" "hc" 
[4,] "sbj103" "sz" 
[5,] "sbj104" "sz" 
[6,] "sbj106" "sz" 

Examine variables

  • print()
print(hc_subjs)
[1] "sbj101" "sbj102" "sbj105"
  • length()
length(hc_subjs)
[1] 3
  • dim()
dim(grp_subjs)
[1] 6 2
  • str()
str(grp_subjs)
 chr [1:6, 1:2] "sbj101" "sbj102" "sbj105" "sbj103" "sbj104" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "subj" "group"

Index and Select

  • Indices
grp_subjs[1,1]
    subj 
"sbj101" 
grp_subjs[1,]
    subj    group 
"sbj101"     "hc" 
  • Booleans
grp_subjs[,2]=='hc'
[1]  TRUE  TRUE  TRUE FALSE FALSE FALSE

Index and Select

  • grep(), grepl(), gsub(), substr()

Convert and Combine

  • paste(), paste0(), cat()
  • join()
  • expand.grid()

Subset and Reshape

  • filter()
  • select()
  • reshape()
  • melt()
  • cast()
  • **ply()

Analyze and Summarize

Compute Parameters

  • mutate()

Compare Means

  • ttest()

ANOVA

  • ezANOVA()

plot of chunk unnamed-chunk-13

Explore and Present

Plot

  • plot()
  • ggplot()
  • ggvis()

Present Results for Publication

  • stargazer()

Dynamic Documents

  • knit()

Resources