Module 1 Introduction to R for Data Science

Author

Jae Jung

Published

January 6, 2025

Basic Functions

1 + 1
[1] 2
2 * 2
[1] 4
2^3
[1] 8
result <- 3 * 2

text <- "This is a great R workshop!"

print(text)
[1] "This is a great R workshop!"
sample.vector <- c(1, 2, 3)

temperatures <- c(75, 76, 80, 77, 73, 71, 69)
names(temperatures) <- c('Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun')
temperatures
  Mon  Tues   Wed Thurs   Fri   Sat   Sun 
   75    76    80    77    73    71    69 
over.74 <- temperatures > 74
over.74
  Mon  Tues   Wed Thurs   Fri   Sat   Sun 
 TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE 
temperatures[over.74]
  Mon  Tues   Wed Thurs 
   75    76    80    77 
temps.over.74 <- temperatures[over.74]

which.max(temperatures)
Wed 
  3 
temperatures[which.max(temperatures)]
Wed 
 80 
temperatures.DF <- as.data.frame(temperatures)

Data Frames

name <- c('Jarrod', 'Jillian', 'Patrick', 'Grant')
age <- c(24, 21, 24, 19)
iq <- c(480, 210, 200, 5)
standing <- c('Super Senior', 'Senior', 'Super Senior', 'Sophomore')

eboard.df <- data.frame(name, age, iq, standing)

is.data.frame(eboard.df)
[1] TRUE
mean(eboard.df$age)
[1] 22
mean(eboard.df$iq)
[1] 223.75

.CSV and More Data Frames

library(dplyr)

Attaching package: 'dplyr'
The following objects are masked from 'package:stats':

    filter, lag
The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union
car_df <- read.csv("data/car_data.csv")

colnames(car_df)[1] <- "model" # Rename first column

performance <- car_df$hp / car_df$wt

car_df <- cbind.data.frame(performance, car_df)

round(mean(car_df$mpg), 2)
[1] 20.09
mean(car_df$mpg)
[1] 20.09062
# Average MPG for cars with 6 and 4 cylinders
# Uncomment and fix the following code to make it functional

# six.cyl.cars <- subset(car_df, cyl == 6)
# four.cyl.cars <- subset(car_df, cyl == 4)

# six.cyl.avg.mpg <- mean(six.cyl.cars$mpg)
# four.cyl.avg.mpg <- mean(four.cyl.cars$mpg)

# six.cyl.avg.mpg > four.cyl.avg.mpg
# six.cyl.avg.mpg < four.cyl.avg.mpg

# Save updated data frame
# write.csv(car_df, "car_data.csv")

Data Visualization with GGPLOT2

# Install ggplot2 if not already installed
# install.packages("ggplot2")
library(ggplot2)

ggplot(car_df, aes(model, mpg)) +
  geom_bar(stat = "identity") +
  labs(y = "MPG", x = "Model")

ggplot(car_df, aes(model, mpg)) +
  geom_bar(stat = "identity") +
  labs(y = "MPG", x = "Model") +
  theme(axis.text.x = element_text(angle = 60, hjust = 1))