[1] "Hello"
[1] "Hiya"
Inputs and outputs
Can set defaults arguments
Can be general or specific to a package.
n()
vs. read_all_contributions()
Save time in the long run.
If, else if , else
Make a magic 8 ball.
#Defining the function
magic_8_ball <- function(){
#Making a set of values to choose from
sample_set <- c(-1,0,1)
#Randomly choosing a value
random_number <- sample(sample_set, size = 1)
# Making a couple of vectors with 8 ball sayings
positive_vibes <- c("It is certain",
"It is decidedly so",
"Most likely",
"Signs point to yes")
neutral_vibes <- c("Reply hazy, try again",
"Ask again later",
"Concentrate and ask again")
negative_vibes <- c( "Don't count on it",
"My reply is no",
"Very doubtful")
# Control flow
if(random_number == 1){
print(
sample(positive_vibes, size = 1)
)
}
else if(random_number == 0){
print(
sample(neutral_vibes, size = 1)
)
}
else{
print(
sample(negative_vibes, size = 1)
)
}
}
# Run the function
magic_8_ball()
[1] "Reply hazy, try again"
Depending in an argument
This means that R will do operations on vectors.
Make a function that takes a vector of students in this class and prints the name of each student.
library(tidyverse)
library(googlesheets4)
class_info <- read_sheet("https://docs.google.com/spreadsheets/d/1k9qA7XldtHB8-FZjmEymoUoeZJArS4tGy5gyVsvyLB0/edit?usp=sharing") |>
janitor::clean_names()
# selecting only the column we are interested in and making it into a vector.
name_vector <- as.vector(
class_info |>
select("preferred_name"))
Make a function that takes a column of data and finds the average. Use it on the height variable by doing class_info$height (hint: try it with sum() and length(), or for an easier approach use mean()) .
Make a function that draws the US state that is input ( hint: use the maps library).
Challenge: Make it so that the user can override the magic 8 ball function to always get a positive answer. (Hint: I did this by adding an override argument. )