library(ggplot2)

Homework 3


1. Reproduce the Following Plots

data(mtcars)

ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE) +
  labs(title = "MPG vs Weight",
       x = "Weight",
       y = "Miles Per Gallon")
## `geom_smooth()` using formula = 'y ~ x'


1b. mtcars Dataset (Scatterplot with Line of Best Fit + SE)

ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE) +
  labs(title = "MPG vs Horsepower",
       x = "Horsepower",
       y = "Miles Per Gallon")
## `geom_smooth()` using formula = 'y ~ x'


1c. airquality Dataset

data(airquality)

ggplot(airquality, aes(x = Temp, y = Ozone)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE, na.rm = TRUE) +
  labs(title = "Temperature vs Ozone",
       x = "Temperature",
       y = "Ozone")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 37 rows containing missing values or values outside the scale range
## (`geom_point()`).


1d. airquality Dataset

ggplot(airquality, aes(x = Wind, y = Ozone)) +
  geom_point() +
  geom_smooth(method = "lm", se = TRUE, na.rm = TRUE) +
  labs(title = "Wind vs Ozone",
       x = "Wind",
       y = "Ozone")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 37 rows containing missing values or values outside the scale range
## (`geom_point()`).


2. Functions

2a. comp_area(radius)

comp_area <- function(radius) {
  pi * radius^2
}

comp_area(5.5)
## [1] 95.03318

2b. sq_dif(x, y)

sq_dif <- function(x = 2, y = 3) {
  (x - y)^2
}

sq_dif()
## [1] 1
sq_dif(5, 1)
## [1] 16

2c. is_odd(x) and odd_in(vec)

# Returns TRUE when x is even
is_odd <- function(x) {
  x %% 2 == 0
}

odd_in <- function(vec) {
  vec[!is_odd(vec)]
}

odd_in(1:10)
## [1] 1 3 5 7 9

3. Loops

3a. Nested for Loop

for (a in 1:3) {
  for (b in 1:3) {
    print(c(a, b))
  }
}
## [1] 1 1
## [1] 1 2
## [1] 1 3
## [1] 2 1
## [1] 2 2
## [1] 2 3
## [1] 3 1
## [1] 3 2
## [1] 3 3

3b. While Loop

set.seed(123)

while (TRUE) {
  num <- rnorm(1)
  print(num)
  
  if (num > 1) {
    break
  }
}
## [1] -0.5604756
## [1] -0.2301775
## [1] 1.558708

3c. Repeat Loop

msg <- c("PSY290")
i <- 1

repeat {
  print(msg)
  i <- i + 1
  
  if (i > 6) {
    break
  }
}
## [1] "PSY290"
## [1] "PSY290"
## [1] "PSY290"
## [1] "PSY290"
## [1] "PSY290"
## [1] "PSY290"