When beginning to learn R, you should know how to do three things with functions.
If you type the name of the function by itself, R will return the code stored in that function.
For example, try to run the function below:
factorial(2)
## [1] 2
This is the code that R runs when we call the factorial function.
To run a function, you must place a set of parentheses after the functions name, as shown below.
# The hash comments the line so it is not run as code
# Remove the hash before factorial and run this code chunk
factorial()
When you do this, you will get an error! This is because the
factorial() function requires an input or argument. In
other words, we have to give it the number we want the factorial
for.
Try this here. Remove the hash mark and place a number in the parentheses:
factorial(3)
## [1] 6
In the next code chunk, check that your answer makes sense. For example, the factorial of 5 is calculated as the product. 54321
5*4*3*2*1
## [1] 120
Try is for the argument you gave to factorial().
3*2*1
## [1] 6
If you wanted to know more about the function that you are using, you
can put a ? infront of the function. When you run this, R
will open the help page for that particular function. When doing this,
you do not need to include the parentheses after the function.
?log
## Help on topic 'log' was found in the following packages:
##
## Package Library
## base /usr/lib/R/library
## otel /usr/local/lib/R/site-library
##
##
## Using the first match ...
When you run this code chunk, R will give you information about that function in the help tab on the right side of the screen.
Some examples of R functions include: * the square root function,
sqrt(), * the absolute value function, abs(),
and * the sequence generation function seq().
To find the square root of 25, run this code chunk:
sqrt(25)
## [1] 5
By running the next two code chunks, can you figure out what the ‘abs()’ function does?
abs(-5)
## [1] 5
abs(5)
## [1] 5
An argument is an input that you give to a function.
In abs(5), “5” is the argument.
Most R functions can take multiple arguments. For example,
seq() takes three arguments.
seq(1,20,2)
## [1] 1 3 5 7 9 11 13 15 17 19
Here seq() takes three arguments:
seq(from = 1, to = 20, by = 2)
and returns a sequence of numbers
Before running the next code chunk, can you predict what will be returned?
seq(20,1,-2)
## [1] 20 18 16 14 12 10 8 6 4 2
You learned: 1. That how to run R code in an RStudio session. 2. What an R function is and how it is constructed. 3. How to get help on R functions and the arguments they require. 4. How to create and run your own R code.
Amazing job! You are gaining the fundamentals of R!