Get Started

Optional arguments

Let's look at some of the round() function's help documentation. It simply rounds a numeric vector off to a specified number of decimal places.

round(x, digits = 0)

The first argument, x is required. Without it, the function will not work!

The argument digits is known as an optional argument. Optional arguments are ones that don't have to be set by the user, either because they are given a default value, or because the function can infer them from the other data you have given it. Even though they don't have to be set, they often provide extra flexibility. Here, digits specifies the number of decimal places to round to.

Explore the round() function in the exercise!

This is a part of the course

“Intermediate R for Finance”

View Course

Exercise instructions

  • Use round() on 5.4.
  • Use round() on 5.4, specify digits = 1.
  • A vector numbers has been created for you.
  • Use round() on numbers and specify digits = 3.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Round 5.4
___

# Round 5.4 with 1 decimal place
___

numbers <- c(.002623, pi, 812.33345)

# Round numbers to 3 decimal places
___
Edit and Run Code

This exercise is part of the course

Intermediate R for Finance

BeginnerSkill Level
4.7+
11 reviews

Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.

If data structures like data frames and vectors are how you hold your data, functions are how you tell R what to do with your data. In this chapter, you will learn about using built-in functions, creating your own unique functions, and you will finish off with a brief introduction to packages.

Exercise 1: What are functions?Exercise 2: Function help and documentationExercise 3: Optional arguments
Exercise 4: Functions in functionsExercise 5: Writing functionsExercise 6: Your first functionExercise 7: Multiple arguments (1)Exercise 8: Multiple arguments (2)Exercise 9: Function scope (1)Exercise 10: Function scope (2)Exercise 11: PackagesExercise 12: tidyquant package

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free