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:

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

R Variables

Invalid Variable Names:

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:


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


> 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)


 [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