R Variables

R Variables:

  • Variables are containers to for storing data.
  • Variable name consists of letters, numbers, dot and underscores.
  • Variables must begin with letters or dot(but dot should not be followed by a number.
  • Variable names are case sensitive(var1 and Var1 are two different variables).
  • Variable names should not contain spaces.
  • R reserved words(if else repeat while function for in next break TRUE FALSE NULL.. etc) cant be used as variables.
  • Variable must be assigned some value or null at the time of creation. If we do not assign value for new variable, we will receive error message like object ‘var100’ not found.
  • We can create and assign values to variables using assign(“variable_name”,value) function.

Valid Variable Names:

>var1<-100
> this_finance=”
> .var1<-200
> var2.first=’K2schools’
> var_second=’R Language’
> var100<-”
> .var100_200

R Variables

Invalid Variable Names:

_var1<-100
9var1<-100
$var1<-‘currency’
var@1<-‘k2schools’
_var1_first<-“k2schools”
var100(Must be assigned some value or nothing like var100<-”)
.2var100_200<-100(dot(.) must not followed by number).

R Variables Assignment:

  • We can assign variables using leftward(<-), rightward(->) and equal to operator.
  • Variable values can be printed using print or cat function.

Assignment of R variables using equal operator:

var1=100
var2=c(10,20,30)

Assignment of R variables using leftward operator:

var3 <- 'Hello World' var4 <- c(1,2,3,4,10) Assignment of R variables using rightward operator:

c(‘hello’,100) -> var5
c(99,100) -> var6

How to get R variable data type:
We can get data type of variable using class function

Example:

> var3 <- 'Hello World' > class(var3)
[1] “character”

To get list of user defined variables:

We can get list of variables using ls(), objects(), print(ls()), print(objects()),cat(ls()), cat(objects())
To get hidden variables use ls(all.names=TRUE)

Examples:

 ls()
 [1] "a"            "acno"         "b"            "c"            "d"            "e"           
 [7] "f.12"         "k1"           "list1"        "name"         "p"            "result"      
[13] "t"            "this_finance" "v"            "v1"           "v2"           "v3"          
[19] "var_10"       "var1"         "var2"         "var3"         "var39"        "var5"

Delete R Variables:
R Variables can be deleted using rm function.

> var3 <- 'Hello World' > rm(var3)
> var3
Error: object ‘var3’ not found

Powered by WordPress