Reproduce the following plots with the specified datasets.
a. Use the mtcars data set.
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
stat_smooth()
b. Use the mtcars data set
ggplot(mtcars, mapping = aes(x = wt, y = mpg, color = factor(cyl))) +
geom_point() +
scale_color_manual(values = c("4" = "orange",
"6" = "green",
"8" = "blue"))
c. Use the airquality data set.
ggplot(airquality, mapping = aes(y = factor(Month))) +
geom_bar()
d. Use the airquality data set.
ggplot(airquality, mapping = aes(x = Wind, y = Temp)) +
geom_point() +
stat_smooth() +
facet_wrap(~ Month)
Create the following functions:
a. Create a function called
comp_area(radius) to calculate the area (A) of a circle for a given
radius (r) using the formula 𝐴 = 𝜋 × 𝑟!. Test the function by finding
the area of a circle with a radius of 5.5 cm.
comp_area <- function(radius) {
area <- pi * radius^2
return(area)
}
comp_area(5.5)
## [1] 95.03318
b. Create a function, sq_dif(x, y), that doe the following:
• take two arguments x and y with default values of 2 and
3;
• take the difference of x and y values;
• square the difference;
• return the final
value.
sq_dif <- function(x = 2, y = 3) {
difference <- x - y
squared <- difference^2
return(squared)
}
c. Create a function is_odd(x) that returns TRUE when x is even
and FALSE otherwise. Then, using is_odd(x), write a function odd_in(vec)
that returns a vector comprised of the odd integers in a vector vec of
integers.
is_odd <- function(x) {
return(x %% 2 == 0)
}
odd_in <- function(vec) {
return(vec[!is_odd(vec)])
}
Create the following loops:
Create a nested for loop, where
the outer for() loop increments “a” 3 times, and the inner for() loop
increments “b” 3 times. The nested loop prints the values of “a” and “b”
as a vector.
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
b. Create a while loop that prints out numbers drawn from the
standard normal distribution (use rnorm()) but stops (breaks) if you get
a number bigger than 1.
while (TRUE) {
x <- rnorm(1)
print(x)
if (x > 1) {
break
}
}
## [1] -0.149291
## [1] 0.4529652
## [1] -1.253267
## [1] -1.452654
## [1] 0.298133
## [1] -0.2133145
## [1] -0.383155
## [1] 1.964334
c. Using the variables below create a repeat loop that breaks off
the incrementation of “i” after 6 iterations, and prints “msg” at every
increment.
• msg <- c(“PSY290”)
• i <-
1
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"