R Variables
In this tutorial, we shall learn about R Variables, how to assign value to a variable, know the data type of variable, find the list of variables and delete some of them if required.
Variables are names given to storage locations of data. Once we declare that a variable would hold some specific data, we may access that specific data in the due course of the program using the variable name. In R programming language, any R-Object could be stored in a variable with a name given to the variable.
Rules for writing R Variables
Following are the rules to give a valid name to an R variable.
- It may contain letters (Examples : x, y, varx, .. )
- It may contain numbers (Examples : x1, y1, var25x, .. )
- It may contain special char Dot (.) (Examples : x., y., var.x, .. )
- It may contain special char Underscore(_) (Examples : x_1, y_2, var_x, .. )
- The first character in the name could be a letter. (Examples : x, y, varx, .. )
- The first character in the name could be a dot not followed by a number. (Examples : .x, .y, varx, .. )
- Reserved words in R could not be used for variables.
Examples for invalid variable names : .2x, tan, er@t
Assign value to R Variable
R Variable can be assigned a value using one of the following three operators :
- Equal Operator =
- Leftward Operator <-
- Rightward Operator ->
In the following, we have examples for equal operator, leftward operator and rightward operator respectively.
> x = 'hello'
> print(x)
[1] "hello"
> x <- 'learn r' > print(x)
[1] "learn r"
> 'r programming language' -> x
> print(x)
[1] "r programming language"
Find all R Variables
When you are running commands in an R command prompt, the instance might get stacked up with lot of variables.
To find all R variables that are alive at a point in R command prompt or R script file, ls() is the command that returns a Character Vector.
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "RGB" "r programming language" "v"
[10] "values" "x" "y"
> p = 36.89
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "p" "RGB" "r programming language"
[10] "v" "values" "x"
[13] "y"
Delete an R Variable
rm(variable_name) deletes an R variable from the stack of variables in a running instance.
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "p" "RGB" "r programming language"
[10] "v" "values" "x"
[13] "y"
> rm(fruits)
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "listX" "p"
[7] "RGB" "r programming language" "v"
[10] "values" "x" "y"
Conclusion
In this R Tutorial, we have learnt about R Variables and to assign values to them, to find all R variables and to delete some of them if necessary.