Functions

You have used a few functions already. Here is just a bit more formal introduction. You should be able to understand the inputs (arguments) you specify when calling a function and the output it returns. For most functions, you can get help by executing ?function_name in the console.

Calling functions

R has a large collection of built-in functions that are called using:

function_name(arg1 = val1, arg2 = val2, ...)


Let's try using seq() which makes regular sequences of numbers and, while we're at it, learn more helpful features of RStudio. Type se and hit TAB. A popup shows you possible completions. Specify seq() by typing more (a "q") to disambiguate or by using ↑/↓ arrows to select. Notice the floating tooltip that pops up, reminding you of the function's arguments and purpose. If you want more help, press F1 to get all the details in the help tab in the lower right pane.

Press TAB once more when you've selected the function you want. RStudio will add a matching opening (() and closing ()) parentheses for you. Type the arguments 1, 10 and hit return.

seq(1, 10)
 #>  [1]  1  2  3  4  5  6  7  8  9 10


Type this code and notice you get similar assistance with the paired quotation marks:

x <- "hello world"

Quotation marks and parentheses must always come in a pair. RStudio does its best to help you, but it's still possible to mess up and end up with a mismatch. 

If this happens, R will show you the continuation character "+":

> x <- "hello
+

The + says that R is waiting for more input.  Usually, that means you've forgotten either a " or a ). Either add the missing pair or press ESCAPE to abort the expression and try again.

If you make an assignment, you do not see the value, and you are then tempted to double-check the result immediately:

y <- seq(1, 10, length.out = 5)
 y
 #> [1]  1.00  3.25  5.50  7.75 10.00


This common action can be shortened by surrounding the assignment with parentheses, which causes the assignment and "print to screen" to happen.

(y <- seq(1, 10, length.out = 5))
 #> [1]  1.00  3.25  5.50  7.75 10.00


Now look at your environment in the upper right pane:

rstudio-env


Here you can see all of the objects that you've created.


Source: H. Wickham and G. Grolemund, https://r4ds.had.co.nz/workflow-basics.html
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 3.0 License.