Arguments

Arguments

The inputs to a function are called arguments. Every argument has a name, and you can supply it by name or by position:

round(3.14159, digits = 2)
round(3.14159, 2)        # the same: matched by position

R matches named arguments by name, so they can go in any order. It matches unnamed arguments in the order the function defines them. A good habit is to leave the first argument (usually the data) unnamed and name the rest.

Many arguments have a default value, which R uses when you don’t supply one. round()’s digits defaults to 0, which is why round(3.14159) returns 3. An argument with no default is required: leave it out and R stops with an error.

args() lists a function’s arguments with their defaults. This is the same idea as Python’s keyword arguments, as in def round(x, digits=0).

Change the chunk below so that it returns 3.142.

args()

rnorm() is a function that generates random variables from a normal distribution. Find the arguments of rnorm() using the args() function.

args(rnorm)

Good job! n specifies the number of random normal variables to generate. mean and sd describe the distribution to generate the random values with.

Optional arguments

Which arguments of rnorm() are not optional?




rnorm() 1

Use rnrom() to generate 100 random normal values with a mean of 100 and a standard deviation of 15.

rnorm(100, mean = 100, sd = 15)

rnorm() 2

Can you spot the error in the code below? Fix the code and then re-run it.

Hint: In math, \(\mu\) (mu, pronounced “mew” or “moo”) is a Greek letter that stands for the mean of a distribution.

rnorm(100, mean = 100, sd = 15)

Next topic