--3-Functions

#1-Introduction to Functions

​Intro to functions video​

#2-Function documentation

#Consult the documentation on the mean() function: 
#?mean or help(mean).
#Inspect the arguments of the mean() function using
#the args() function.
#Consult the documentation on the mean() function

?mean
help(mean)

# Inspect the arguments of the mean() function
args(mean)

#3-Use a function

#Calculate the average number of views for both linkedin 
#and facebook and assign the result to avg_li and avg_fb, 
#respectively. 
#Experiment with different types of argument matching!
#Print out both avg_li and avg_fb.

# The linkedin and facebook vectors have already 
#been created for you

linkedin <- c(16, 9, 13, 5, 2, 17, 14)

facebook <- c(17, 7, 5, 16, 8, 13, 14)

# Calculate average number of views

avg_li<-mean(linkedin)

avg_fb<-mean(facebook)

# Inspect avg_li and avg_fb

print(avg_li)

print(avg_fb)

#4-Use a function (2)

#Calculate the mean of the element-wise sum of linkedin 
#and facebook and store the result in a variable avg_sum.
#Calculate the mean once more, but this time set the 
#trim argument equal to 0.2 
#and assign the result to avg_sum_trimmed.
#Print out both avg_sum and avg_sum_trimmed; 
#can you spot the difference?

linkedin <- c(16, 9, 13, 5, 2, 17, 14)
facebook <- c(17, 7, 5, 16, 8, 13, 14)

# Calculate the mean of the sum
avg_sum<-mean(linkedin+facebook)

# Calculate the trimmed mean of the sum
avg_sum_trimmed<-mean(linkedin+facebook,0.2)

# Inspect both new variables
print(avg_sum)
print(avg_sum_trimmed)

#5-Use a function (3)

#Calculate the average number of LinkedIn profile views, 
#without specifying any optional arguments. 
#Simply print the result to the console.
#Calculate the average number of LinkedIn profile views, 
#but this time tell R to strip missing values 
#from the input vector.

# The linkedin and facebook vectors have 
#already been created for you

linkedin <- c(16, 9, 13, 5, NA, 17, 14)

facebook <- c(17, NA, 5, 16, 8, 13, 14)

# Basic average of linkedin
mean(linkedin)

# Advanced average of linkedin
mean(linkedin,trim=0,na.rm=TRUE)

#6-Functions inside functions

#Use abs() on linkedin - facebook to get the absolute 
#differences between 
#the daily Linkedin and Facebook profile views. 
#Next, use this function call inside mean() to 
#calculate the Mean Absolute Deviation. 
#In the mean() call, make sure to specify na.rm to 
#treat missing values correctly!

# The linkedin and facebook vectors have already 
#been created for you
linkedin <- c(16, 9, 13, 5, NA, 17, 14)
facebook <- c(17, NA, 5, 16, 8, 13, 14)

# Calculate the mean absolute deviation
mean(abs(linkedin-facebook),na.rm=TRUE)

#7-Required, or optional?

#Which of the following statements about 
#the read.table() function are true?
#1-header, sep and quote are all optional arguments.
#2-row.names and fileEncoding don't have default values.
#3-read.table("myfile.txt", "-", TRUE) will throw an error.
#4-read.table("myfile.txt", sep = "-", header = TRUE) 
#will throw an error.
#1 and 3: The right answer

#8-Writing Functions

​Writing function video​

#9-Write your own function

#Create a function pow_two(): it takes one 
#argument and returns 
#that number squared (that number times itself).
#Call this newly defined function with 12 as input.
#Next, create a function sum_abs(), that takes 
#two arguments 
#and returns the sum of the absolute values of 
#both arguments.
#Finally, call the function sum_abs() with 
#arguments -2 and 3 afterwards.

# Create a function pow_two()
pow_two<-function(x){
  x*x
}

# Use the function
pow_two(12)

# Create a function sum_abs()
sum_abs<-function(y,z){
  abs(y)+abs(z)
}

# Use the function
sum_abs(-2,3)

#10-Write your own function (2)

# Define the function hello()
hello<-function(){

  print("Hi there!")
  return(TRUE)
}
# Call the function hello()
hello()

#11-Write your own function (3)

#Add an optional argument, named print_info, 
#that is TRUE by default.
#Wrap an if construct around the print() function: 
#this function should 
#only be executed if print_info is TRUE.
#Feel free to experiment with the pow_two() 
#function you've just coded.

# Finish the pow_two() function
pow_two <- function(x, print_info = TRUE) {
  y <- x ^ 2
  if (print_info) {
    print(paste(x, "to the power two equals", y))
  }
  return(y)
}

# Some calls of the pow_two() function
pow_two(5)
pow_two(5, FALSE)
pow_two(5, TRUE)

#12-Function scoping

#Which statement is correct about the following 
#chunk of code? 
#The function two_dice() is already available in the 
#workspace.

two_dice <- function() {
  possibilities <- 1:6
  dice1 <- sample(possibilities, size = 1)
  dice2 <- sample(possibilities, size = 1)
  dice1 + dice2
}

two_dice()

#Executing two_dice() causes an error.
#Executing res <- two_dice() makes the contents of 
#dice1 and dice2 
#available outside the function.
#Whatever the way of calling the two_dice() function, 
#R won't have access to dice1 and dice2 outside the 
#function.->RIGHT

#13-R passes arguments by value

#Can you tell which one of the following 
#statements is false about 
#the following piece of code?

increment <- function(x, inc = 1) {
  x <- x + inc
  x
}
count <- 5
a <- increment(count, 2)
b <- increment(count)
count <- increment(count, 2)


#a and b equal 7 and 6 respectively 
#after executing this code block.
#After the first call of increment(), where a is defined, 
#a equals 7 and count equals 5.
#In the end, count will equal 10.->FALSE
#In the last expression, the value of count 
#was actually changed because of the explicit assignment.

#14-R you functional?

#Finish the function definition for interpret(), 
#that interprets the number of profile views on a single day:
#The function takes one argument, num_views.
#If num_views is greater than 15, the function prints out 
#"You're popular!" 
#to the console and returns num_views.
#Else, the function prints out "Try to be more visible!" 
#and returns 0.
#Finally, call the interpret() function twice: 
#on the first value of the linkedin 
#vector and on the second element of the facebook vector.

linkedin <- c(16, 9, 13, 5, 2, 17, 14)
facebook <- c(17, 7, 5, 16, 8, 13, 14)

# The linkedin and facebook vectors 
#have already been created for you

# Define the interpret function
interpret <- function(num_views) {
  if (num_views > 15) {
    
    print( "You're popular!")
    return(num_views)
  } else {
    print("Try to be more visible!")
    return(0)
    
  }
}

# Call the interpret function twice
interpret(linkedin[1])
interpret(facebook[2])

#15-R you functional? (2)

#Finish the template for the interpret_all() function:
#Make return_sum an optional argument, that is 
#TRUE by default.
#Inside the for loop, iterate over all views: 
#on every iteration, add the result of interpret(v) 
#to count. 
#Remember that interpret(v) returns v for popular days, 
#and 0 otherwise. 
#At the same time, interpret(v) will also do some printouts.
#Finish the if construct:
#If return_sum is TRUE, return count.
#Else, return NULL.
#Call this newly defined function on both 
#linkedin and facebook.

# The linkedin and facebook vectors have 
#already been created for you
linkedin <- c(16, 9, 13, 5, 2, 17, 14)
facebook <- c(17, 7, 5, 16, 8, 13, 14)

# The interpret() can be used inside interpret_all()
interpret <- function(num_views) {
  if (num_views > 15) {
    print("You're popular!")
    return(num_views)
  } else {
    print("Try to be more visible!")
    return(0)
  }
}

# Define the interpret_all() function
# views: vector with data to interpret
# return_sum: return total number of views on popular days?
interpret_all <- function(views, return_sum=TRUE) {
  count <- 0 
  for (v in views) {
    count=count+interpret(v)
  }
  
  if (return_sum) {
    return(count)
  } else {
    return(NULL)
  }
}

# Call the interpret_all() function on both 
#linkedin and facebook
interpret_all(linkedin)
interpret_all(facebook)

#16-R Packages

​R packages video​

#17-Load an R Package

#To fix the error you saw in the console, 
#load the ggplot2 package.
#Now, retry calling the qplot() function with 
#the same arguments.
#Finally, check out the currently attached packages again.

datasets::mtcars
installed.packages("ggplot2")

# Load the ggplot2 package
library(ggplot2)

# Retry the qplot() function
qplot(mtcars$wt,mtcars$hp)

# Check out the currently attached packages again
search()

#18-Different ways to load a package

install.packages("data.table")        # install it
library(data.table)                   # load it

  # Chunk 1
library(data.table)
require(rjson)

# Chunk 2
library("data.table")
require(rjson)

# Chunk 3
library(data.table)
require(rjson, character.only = TRUE)

# Chunk 4
library(c("data.table", "rjson"))

#The right answer: Chunk 1 and Chunk 3

Last updated