Today we’re practicing functions! In the exercises below, you’re asked to write short R scripts that define functions aimed at specific tasks. The exercises start at an easy level, and gradually move towards slightly more complex functions.

Answers to the exercises are available here.

If you obtained a different solution than the one posted on the answers page, please let us know of your solution by posting it as a comment at the end of that page.

Note: For some exercises, the solution will be quite easy if you make clever use of some of R’s built-in functions. For some exercises, you might want to create a vectorized solution (i.e., avoiding loops), and/or a (usually slower) non-vectorized solution. However, the exercises do not aim to practise vectorization and speed, but rather defining and calling functions.

**Exercise 1**

Create a function that will return the sum of 2 integers.

**Exercise 2**

Create a function what will return TRUE if a given integer is inside a vector.

**Exercise 3**

Create a function that given a data frame will print by screen the name of the column and the class of data it contains (e.g. Variable1 is Numeric).

**Exercise 4**

Create the function unique, which given a vector will return a new vector with the elements of the first vector with duplicated elements removed.

**Exercise 5**

Create a function that given a vector and an integer will return how many times the integer appears inside the vector.

**Exercise 6**

Create a function that given a vector will print by screen the mean and the standard deviation, it will optionally also print the median.

**Exercise 7**

Create a function that given an integer will calculate how many divisors it has (other than 1 and itself). Make the divisors appear by screen.

**Exercise 8**

Create a function that given a data frame, and a number or character will return the data frame with the character or number changed to NA.

**Want to practice functions a bit more? We have more exercise sets on this topic here.**

Image by Ninjahatori (Own work) via Wikimedia Commons

**What's next:**

- Become a Top R Programmer Fast with our Individual Coaching Program
- Explore all our (>4000) 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

PRASHANTH says

Solution to Ex.2

intvect <- function(v,x)

{

x%in%v

}

Emre Kar says

Solution to Ex.2

is.in <- function(a, c){

for(i in 1:length(c))

if(c[i]==a){

return(print("TRUE"))

}

print("FALSE")

}

xyz says

Can you please elaborate on the meaning of this in Example 4:

if(sum(v[i] == s) == 0)