print("welcome to R")
[1] "welcome to R"
In R, we can enter commands in the console to have the computer perform the corresponding tasks. For example, we want to print ‘welcome to R’
As a computing language specifically designed for statisticians, the most essential elements in R are functions, since almost all tasks are accomplished through various functions. Similar to most programming languages, the general form of a function in R is
FunctionName([input 1], [input 2], ..., [argument 1], [argument 2], ...)
i.e. it consists of a function name, inputs and arguments enclosed in parentheses. For example, you can type the following math functions in the console,
[1] 1.224647e-16
[1] 2.718282
[1] 1
Remark: As you can see from the code above, we use #
sign to comment the code, in other words, characters after #
are not considered as part of the command.
R has extensive and well-organized help documentation. You can access help for specific functions using the ?
or help()
function. For example:
You will see the help document of this function in Rstudio.
The first function is c
function, which can create a sequence of numbers based on your inputs and store in in memory. For example, we want to create a sequence of the integers from 1 to 10 and store it in a variable x
.
You also can include characters in x
by function c
, for example
Remark: In R, if you use parentheses to enclose a command, then the outputs will be printed automatically.
Typing the integers from 1 to 10 can be done by another function seq
or simply by colon operator :
Well, the simple colon operator is neat but limited to integer sequence and increments of 1 (or -1, try 10:1 in your console). Use seq
when you need more control over the sequence, for example, try the following code in your console
The last function for creating sequence is rep
, which can create copies of your inputs, for example
In R, you are allowed to encapsulate specific tasks or calculations that you can reuse throughout your code. The syntax for defining a function is
# Syntax of custom function
function_name = function(inputs, arguments) {
# Function body: code to execute
# Optionally return a value
return(value)
}
For example, we want a function to calculate the sum of two input values
function
, the values assigned to x
and y
are default values, namely R will take two ones as input automatically if we don’t enter any inputs into function mySum
, for example, the result of the last line above should be 2.return
to indicate the results should be returned, then the results of the last line in the function will be returned as output.