x <- 4
y <- 2
z <- x * y ** 2
z[1] 16Hubert Baechli
March 8, 2025
Below are some exercises that should help you learn the most important basic built in functions and how to incorporate them into your own functions. This sheet focuses on numbers and how they could rounded.
as you already know, you can do simple math with R
But R can do almost everything that can be done with numbers, also with vectors of numbers.
And it becomes even easier when you wrap it in functions. So create a function that performs the calculation shown above.
Hint: Your function should also work with vectors or with combinations
You used already the round function, may with such a line
R is very flexible and has interpreted this as follows:
But R also has many other built-in functions, such as rounding up.
Guess the function which is rounding down ;-)
[1] 3To my knowledge, there is no built-in function that checks whether a number is even or odd.
But we can write one ourselves.
Hint: Try to use the integer operators for the solution.
You should write a function is_even which returns TRUE or FALSE:
You will often find that you need to round something not to the nearest whole number, but to some other part of a number. For example, grades are often rounded to the nearest half - 4.5, 5, 5.5, 6… Unfortunately we cannot use round directly for this and we’ll have to be a bit more clever.
Write a function that will round a number to the nearest half.
Your function should do this
And just like the built-in functions, it would be nice if this also works with vectors. Check if your function works with vector input. If it doesn’t, why is that? And what can you do to make it work with vectors?
The built-in round function has an argument “digits”, which lets the user specify how many digits to round to. For example:
It would be nice if we had a grade rounding function that also lets us specify what is the nearest proportion to which we want to round the grade. For example, if the school decides to use quarter grades (5.25), instead of writing a new function round_to_quarter, it would be nice if we had just one function that can do both things:
or to any arbitrary proportion: