For storing data values variables are used as containers. For declaring variables in R doesn’t have a command. For creating a variable, you have to assign a value to it. For assigning a value to a variable, we need to use the sign (<-).
To print the variable value, only type the variable name:
t <- "Tutorials Art" n <- 20 t n
Output:
From the example above, t and n are variables, while "Tutorials Art"
and 20 are values.
Print / Output Variables in R
Unlike other programming languages, you don’t need to use a function for output variables in R. Only type the name of the variable:
t <- "Tutorials Art" t
Output:
We know that in R print() function is available if you want to use it. This is helpful in case you know about other programming languages, like Python, which may use a print() function for output variables.
t <- "Tutorials Art" print(t)
Output:
For output code, you must use the print() function in some situations, for example, while working with for loops.
for (x in 1:5) { print(x) }
Output:
Concatenate Elements in R
You can also join two or more elements with the use of the paste() function. In R, Comma (,) is used to combine text and variable.
t <- "Tutorials Art" paste("Welcome to", t)
Output:
We can also use (,) to add a variable in another variable:
t1 <- "Welcome to " t2 <- "Tutorials Art" paste(t1, t2)
Output:
For numbers + sign works as a mathematical operator:
num1 <- 5 num2 <- 10 num1 + num2
Output:
The error will occur, when you try to combine (text) and number.
n <- 5 t <- "Tutorials Art" n + t
Result:
Multiple Variables in R
Multiple variables in one line can be assigned the same value in the R language.
# Assign value to multiple variables in single line v1 <- v2 <- v3 <- "Tutorials Art" # Print values v1 v2 v3
Output:
Variable Names in R
You can use short names as variables (x and y) and you can use more in detail (age, YourName, total_volume). Following are some R variables rules:
- Variable name must begin with a letter and can be combination of period(.), letters, digits and underscore ( _ ) if it start with period(.), it will not followed by a digit
- Variable name cannot be start with number and underscore ( _ )
- Variables are case sensitive (age, Age and AGE will count three different variables)
- We cannot used reserved words as variables (NULL, FALSE, TRUE, if…)