*everything that happens is a function call*. So, if we want to improve our ability to make things happen the way we want them to, maybe it’s worth getting very comfortable with how functions work in R.

**Exercise 1**

Write a function that calculates number `a`

to the power of `b`

, but let `b`

have a default value of `2`

.

**Exercise 2**

Re-write the function from exercise 1 so that `a`

has a default value of `b+1`

already from the formals (from the argument definition.)

**Exercise 3**

Write a function `div()`

that checks if the first number divides the second.

**Exercise 4**

Write an *infix* function `%div%`

that checks if the left-hand side divides the right-hand side.

# Example

3 %div% 42

[1] TRUE

3 %div% 13

[1] FALSE

**Exercise 5**

Write a function that changes the value of `pi`

in the R global environment to whatever you specify as the argument. Note: it is not recommended to re-define the value of “pi” in a real-life R program.

# Example

pi

[1] 3.141593

chpi(4)

pi

[1] 4

chpi("I like cats")

pi

[1] "I like cats"

**Exercise 6**

Write an infix (binary) function that checks if the left hand side (lhs) is in the range between the maximum and minimum of the rhs.

set.seed(1)

rnorm(6) %betw% c(-1, 1)

[1] TRUE TRUE TRUE FALSE TRUE TRUE

**Exercise 7**

Write another infix operator that pastes two strings and uses it in a function that takes `ellipsis`

. Now, call the function and feed it two strings and concatenate them to produce some text.

**Exercise 8**

What did you think about the example in exercise 3? What does the following code (from the book Advanced R) return?

f2 <- function(x = z) {

z <- 100

x

}

f2()

**Exercise 9**

Write a function that creates a function analogous to the one from exercise 1 by feeding 2 as an argument. Note: this is not a typo.

# Example of a function called power()

powerof2 <- power(2)

powerof2(3)

[1] 9

**Exercise 10**

Make a new `names<-`

(replacement) function called `names2<-`

that also allows you to update the names of data structures, except it forces the names it is given to all-lowercase.

# Example

x <- 3:4

names2(x) <- c("IMPORTANT", "For The CAT do NOT EAT")

x

important for the cat do not eat

3 4

(Photo by Pascal)

**What's next:**

- Explore all our (>1000) R exercises
- Find an R course using our R Course Finder directory
- Subscribe to receive weekly updates and bonus sets by email
- Share with your friends and colleagues using the buttons below

paul says

For exercise #5, my solution as below:

“`

chpi <- function(new_pi){

pi <<- new_pi

}

chpi(4)

pi

“`

it yields “`Error in chpi(4) : cannot change value of locked binding for 'pi'“`

sindri says

Thanks for letting me know. I will look into it. But the idea of the exercise was just to write a function that changes a value of any variable in the global environment you could instead of pi change T or any other variable that is predefined or you have already defined.