Variables in R Programming
R Variables Definition
Variables are defined as identifier or named space in the memory, which are stored and can be referenced and also can be manipulated later in the program. R language is a Dynamically Typed and also Interpreted language where Type Checking of the variable and other objects is commited at the run time.
R Rules of Variables
Rule 1: The variable name has to start with letter and can contain letter, number, underscore (“_”) or period (“.”).
Example:
“varName1”, “my.variable” are valid variable names
“2var” is not a valid variable name
Rule 2: Underscore (“_”) at the beginning of the variable name is not allowed.
Example:
“_myvariable” is not a valid variable
Rule 3: Period (“.”) at the beginning of the variable name is allowed but must not be followed by numbers. It is recommended in R to use period (“.”) to separate the different words for the identifier.
Example:
“.varone” is a valid variable
“.1var” is not a valid variable
Rule 4: Special characters such as “&”, “#”, etc., along with white space (space, tabs) are not allowed in a variable name.
Example:
“var$2”, “var#2” are not valid variables
Rule 5: Reserved words or keywords are not allowed as a variable name.
Example:
“TRUE”, “FALSE” are not valid variables
Variable Assignment
Three ways of variable assignment in R.
“=” Operator: “=” used to assign the value.
Example : my.variable = 100
“<-” Operator: The value on the right is assigned to the left variable.
Example: my.variable <- 123
“->” Operator: The value on the left is assigned to the right variable.
Example: 999 -> my.variable
How To Determine Variable
Variable in R can be determined by function class(), typeof() and mode().
‘class()’ – will give the high-level type of an object. It is used to determine the data type of the variable provided to it.
Example:
varx <- "hello"
print(class(varx))
#Output:
[1] "character"
‘typeof()’ – will return values which matches the internal type of object in R. It is mostly used by R programmer to determine the type of an object.
Example:
typeof(2)
typeof(2.8)
typeof("3")
typeof("gfg")
typeof(1 + 2i)
#output:
[1] "double"
[1] "double"
[1] "character"
[1] "character"
[1] "complex"
‘mode()’ – will returns the values which are the same and closely related to ‘typeof().’
Example:
mode(7)
mode(2.7)
mode("9")
mode("xyz")
mode(4 + 6i)
#output:
[1] "numeric"
[1] "numeric"
[1] "character"
[1] "character"
[1] "complex"
How to Show All Presented Variables
“ls()” function is used to show all the present variables in the workspace.
Example:
var1<- "hello"
print(ls())
#output:
[1] "var1"
How to Remove Variables
‘rm()’ function is used to remove or delete variable in R.
Example:
var2<- "hello"
rm(var2)
print(var2)
#output:
Error: object 'var2' not found
Congratulations
Congratulations, you have finished this tutorial of R variables.
