--2-When and how you should write a function

#1-Why should you write a function?

​Why should you write a function? video​

#2-Start with a snippet of code

#To help you test your code, create a vector x containing the numbers 1 through 10.
#Rewrite the code snippet to use the temporary variable x instead 
#of referring to the data frame column df$a

# Define example vector x
x<-c(1:10)

# Rewrite this snippet to refer to x
(x - min(x, na.rm = TRUE)) /
(max(x, na.rm = TRUE) - min(x, na.rm = TRUE))

#3-Rewrite for clarity

# Define the intermediate variable rng to contain the range of x 
#using the function range(). 
# Specify the na.rm() argument to automatically ignore any NAs in the vector.
# Rewrite the snippet to refer to this intermediate variable.

# Define example vector x
x <- 1:10

# Define rng
rng<-range(x,na.rm=TRUE)

# Rewrite this snippet to refer to the elements of rng
(x - min(x, rng)) /
  (max(x, rng) - min(rng))

#4-Finally turn it into a function!

#5-How should you write a function?

​ How should you write a function video​

#6-Start with a simple problem

#7-Rewrite snippet as function

#8-Put our function to use

#9-How can you write a good function?

  • #-good names

  • #-intuitive argument

#10-Good function names

#11-Argument names

#12-Argument order

#13-Return statements

#14-What does this function do?

#15-Let's make it clear from its name

#16-Make the body more understandable

#17-Much better! But a few more tweaks...

Last updated