Part 6 Functions

In programming, a function is a section of a program that performs a specific task.

For example, the function getwd, that we have seen before, is used as:


and has the task of outputting the current working directory.

You can recognize a function by its round brackets: functionname()

A function can also take arguments/parameters:


setwd changes the current working directory to the directory specified with argument dir.

  • Assign the output of a function to an object:

  • Getting help / know how a function works:

From the console:


or (shortcut):


From the RStudio bottom-right panel:

  • The help pages show:
    • required/optional argument(s), if any.
    • default values for each argument(s), if any.
    • examples.
    • detailed description.
  • Get the example of a function:
  • Need more help? Ask your favourite Web search engine !

  • Note on arguments

The help page shows the compulsory arguments in the Usage section: in the help page of getwd and setwd (above), you can see that getwd doesn’t take any compulsory argument, and setwd takes one compulsory argument that is called dir.

Compulsory arguments can be given with their names: in such case you don’t need to respect a specific order, or without their names, in which case you have to respect the order specified in the help page!

For example, the function (a variant of the rep function) takes 2 arguments (see in help page): x and times, in that order:

# use arguments with their names:, times=3)
## [1] 1 1 1
# use arguments with their names without respecting the order:, x=1)
## [1] 1 1 1
# use arguments without their names but respecting the order:, 3)
## [1] 1 1 1
# use arguments without their names without respecting the order:, 1)
## [1] 3
# It works, but is not giving the expected output!