(Course under development)
In my working career as an R developer, each problem I have worked on requires abstraction, and because we are working on abstracting problems professionally, we need to learn how to think about them. This has pushed me further into thinking about my project structure between projects and further between companies because the more boilerplate I can generate that is transferable the less work I have to do.
A function allows us to define tasks to be completed succinctly - they are logical legos. random_numbers
is called a variable. rnorm
is the function that returns a random number from a normal distribution. The values n
, mean
, and sd
are inputs or parameters to the function. What is convenient about functions is that they are abstractions of more complicated logic.
rnorm_output <- rnorm(n = 10, mean = 0, sd = 1) rnorm_output
So as we go along and create cool things in R together, we have to remember to make sense of what we write so that it makes logical sense when we are reading it. We're always trying to abstract away the little details, and that requires always building your R code within an executable function.
main <- function(n) { random_vals <- rnorm(n = n, mean = 0, sd = 1) random_vals }
Your program should be short and succinct, you should be able to maneuver to any point of your program quickly and easily, and should have all of the parameters that you need to be variable.
main(n = 10)
If your R script looks something like this, i.e., not wrapped within a function
model <- lm(cyl ~ mpg, mtcars) model_explanation <- summary(model) print(model_explanation)
you're missing out on a significant number of benefits that will help your development routine.
run_model <- function() { model <- lm(cyl ~ mpg, mtcars) model_explanation <- summary(model) print(model_explanation) }
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.