Intro To R
Intro To R
• Basic R commands
• Bivariate statistics in R
Basic R Commands
Importing a csv file
Command:
read.csv(path name)
• Point-and-click method
In RStudio, use the Import Dataset From text (base)
option
Some useful functions and commands
• # (comment)
In a line of code, anything after a # sign is a comment and R ignores it
• <- (assign)
Assign what is whatever right of the arrow to the object on the left of
the arrow
Example: x <- 2
• help() or ?
Example: help(mean) or ?mean
• library(package name)
Loads an installed package to a new R session/environment
Example: library(psych)
Descriptive Statistics
Metric data
• R function: summary(variable name)
• Example: summary(survey$age)
• Output
mean(survey$smokenum, na.rm=TRUE)
Descriptive Statistics
Categorical data
• R function: table(variable name)
• Example: table(survey$child)
• Output
Bivariate Statistics
Independent samples t-test
R command: t.test(DV ~ IV)
• Example 1: t.test(survey$Mlifesat ~ survey$sex)
• Example 2: t.test(Mlifesat ~ sex, data = survey)
Equal Variances Assumed
R command: t.test(DV ~ IV, var.equal = TRUE)
• Example 1: t.test(survey$Mlifesat ~ survey$sex, var.equal = TRUE)
• Example 2: t.test(Mlifesat ~ sex, data = survey, var.equal = TRUE)
One-way ANOVA
R command: aov(DV ~ IV)
• BEWARE: IV must be a factor type in R
You can check using: class(variable name)
• If not, convert IV to a factor:
Example: survey$age_group <- as.factor(survey$age_group)