R Tutorials
R Data Structures
R Graphics
R Statistics
R Examples
Variables are data storage containers.
R has no variable declaration command. Variables are created when you first give value to it. To assign a value to a variable, use the <-
symbol. To output (or print) a variable value, simply type in the variable name:
name <- "John"
age <- 40
name # output "John"
age # output 40
From the example above, the name
and age
are variables, while "John"
and 40
are values.
In other programming languages, it is commonly used =
as a function of the function. In R, we can use both =
and <-
as shareholders.
However, <-
is preferred in most cases because =
operator can be restricted in some cases to R.
Compared to most other programming languages, you do not need to use the function to print / extract R. Variables.
name <- "John Doe"
name # auto-print the value of the name variable
However, R has a print()
function available if you want to use it. This may be helpful if you are familiar with other programming languages, such as Python, which often uses the print()
function to output dynamics.
name <- "John Doe"
print(name) # print the value of the name variable
There are also times when you have to use print()
function to generate code, for example if you work with for
loops (which you will learn more about in the next chapter):
for (x in 1:10) {
print(x)
}
Conclusion: It's up to you whether you want to use the print()
function or not to decrypt it. However, if your code is within the R-value (for example inside the folded brackets {}
as in the example above), use the print()
function if you want to extract the result.
You can also combine, or join, two or more elements, using the paste()
function.
To combine both text and flexibility, R uses a comma (,
):
text <- "awesome"
paste("R is", text)
You can also use ,
to add variables to other variables:
text1 <- "R is"
text2 <- "awesome"
paste(text1,
text2)
In numbers, the character +
acts as a mathematical operator:
num1 <- 5
num2 <- 10
num1 + num2
If you try to combine a unit of letter (text) with a number, R will give you an error:
num <- 5
text <- "Some text"
num + text
R allows you to assign the same number of multiple variables in a single line:
# Assign the same value to multiple variables in one line
var1 <- var2 <-
var3 <- "Orange"
# Print variable values
var1
var2
var3
Variables can be a shorter word (such as x and y) or a more descriptive word (age, carname, total_ volume). The rules for R changes are:
# Legal variable names:
myvar <- "John"
my_var <- "John"
myVar
<- "John"
MYVAR <- "John"
myvar2 <- "John"
.myvar <- "John"
# Illegal variable names:
2myvar <- "John"
my-var <- "John"
my var <- "John"
_my_var <- "John"
my_v@ar <- "John"
TRUE <- "John"
Remember that flexible words are sensitive!