Variables are the name given to a piece of data or information. Like many other programming languages, we use R variables to store data. R supports numeric, string, boolean and many other data types and we do not declare a variable with the data type, instead of that we assign a value to the variable and on basis of value R automatically sets the data type of variable.
A variable name consists of characters, numbers, and the special character (dot(.) and underscore(_) only) and can not start with any number.
See an example of variable naming in R programming
#Variables Naming in R Programming #Valid Varibale Name varone <- 20 print(varone) #Valid Variable Name .var_two <-30 print(.var_two) #Invalid Variable Name 12months <- 12 #Invalid Variable Name (as dot is followed by number) .1Var <- "Ashish"
The output on R Console
Variable Assignment in R
In R programming, the value of a variable can be assigned using the left arrow, right arrow or equal to the operator and the data type of a variable can be changed multiple times in a program that depends on its value.
# Assignment using using left arrow var1 <- 5 print(var1) # Assignment using using right arrow "Ashish Awasthi" -> var2 print(var2) # Assignment using equal to operator var3 = FALSE print(var3)
Data type of a Variable
This is how we can check the data type of any variable
# Declare Different types of Variables var1 <- 5 print(var1) "Ashish Awasthi" -> var2 print(var2) var3 = FALSE print(var3) # Check class of var1 class(var1) # Check class of var2 class(var2) # Check class of var3 class(var3)
Searching Variable
We can find all variable available in the workspace using ls() function, and we can also use pattern in ls function to find the specific variable.
See an example here
#Declare some variables var <- 10 var1 <- "Ashish Awasthi" var2 <- 20.5 test_var <- TRUE #Print all variables present in workspace ls() #Search specific variable ls(pattern="test")
The output on R Console
Deleting a Variable
If you want to delete a variable that is no longer needed then there is rm() function, that removes variable from the workspace.
See an example
#Declare some variables var <- 10 var1 <- "Ashish Awasthi" var2 <- 20.5 test_var <- TRUE #Delete a variable rm(var2) #Now print that variable print(var2)
The output on R Console
Constants in R
As the name suggests constant means, an entity that value can not be changed. Constants can be numeric, character, boolean etc. All numbers are numeric constants, we can check it's using typeof() function.
#Numeric Constants typeof(10) #Character Constants typeof("Ashish Awasthi") #Buil-in Constants print(pi) typeof(pi) print(LETTERS) typeof(LETTERS) print(letters) typeof(letters) print(month.name) typeof(month.name)
No comments :
Post a Comment