R(5), Variable

Published: by Creative Commons Licence

Variables in R can store atomic vectors, groups of atomic vectors or combinations of many Robject.

Valid names of variables consists of letters, numbers, dot or underscore characters.

NAME RULES

Variable names begin with a letter or with a dot that doesn't follow a number.

variable names valid or invalid reasons
var_name% invalid the character % is invalid
2var_name invalid begin with a number
.2var_name invalid begin with dot that follow a number
.var_name valid -
_var_name invalid begin with a underscore characters

Variable Assignment

THREE Methods:

# Assignment using equal operator.
var.1 = c(0,1,2,3)           

# Assignment using leftward operator.
var.2 <- c("learn","R")   

# Assignment using rightward operator.   
c(TRUE,1) -> var.3

we print it, we can use print() or cat(). The examples follow:

print(var.1)
cat ("var.1 is ", var.1 ,"
")
cat ("var.2 is ", var.2 ,"
")
cat ("var.3 is ", var.3 ,"
")

# results:
# [1] 0 1 2 3
# var.1 is  0 1 2 3 
# var.2 is  learn R 
# var.3 is  1 1 

About function cat(): vector c(TRUE,1) is a mixture of logical and numerical variables. So the logical class will be cast to numerical class (TRUE -> 1).

Data Types of Variables

In the R language, a variable itself does not declare any data types, but instead gets the data type of the R-object assigned to it.

R is called Dynamic Type Language, which means that we can change the data type of a variable over and over again when we use the same variable in our programme. That's one thing different from C.

Find Variables

use ls() function list the variables.

# List all the variables we declared
print(ls())

# List the variables starting with the pattern "var".
print(ls(pattern = "var"))
# Hide variables that start with a dot
print(ls(all.name = TRUE))

Delete Variables

use rm() to delete variables.

# Delete variable named 'var.3'
rm(var.3)
# Using rm() and ls() to delete all the variables
rm(list = ls())

we should know that rm(list = ls()) is totally different from:

list = ls()
rm(list)

because the rm() function only remove the variable named 'list'.