Introduction to Functions

Intermediate R

Filip Schouwenaars

DataCamp Instructor

Functions

  • You already know 'em!
  • Create a list: list()
  • Display a variable: print()
Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Black box principle

Intermediate R

Call function in R

sd(c(1, 5, 6, 7))
2.629956
values <- c(1, 5, 6, 7)
sd(values)
2.629956
my_sd <- sd(values)
my_sd
2.629956
Intermediate R

Function documentation

help(sd)
?sd
sd(x, na.rm = FALSE)

Screen Shot 2021-04-09 at 9.22.28 AM.png

Intermediate R

Questions

sd(x, na.rm = FALSE)
  • Argument names: x, na.rm
  • na.rm = FALSE
  • sd(values) works?
Intermediate R

Argument matching

sd(x, na.rm = FALSE)

By position

sd(values)

By name

sd(x = values)
Intermediate R

na.rm argument

values <- c(1, 5, 6, NA)
sd(values)
NA
sd(x, na.rm = FALSE)
sd(values, TRUE)
2.645751
sd(values, na.rm = TRUE)
2.645751
Intermediate R

sd(values) works?

values <- c(1, 5, 6, 7)
sd(values)
2.629956
sd()
Error in is.data.frame(x) : 
argument "x" is missing, with no default
sd(x, na.rm = FALSE)
Intermediate R

Useful trick

args(sd)
function (x, na.rm = FALSE) 
NULL
Intermediate R

Wrap-up

  • Functions work like a black box
  • Argument matching: by position or by name
  • Function arguments can have defaults
Intermediate R

Let's practice!

Intermediate R

Preparing Video For Download...