Hello guys, after a short introduction of R programming in my previous post, today I will be discussing about the variables and data types in R. In programming, variable is a named piece in a memory that can store value of different data types. In R variables are case sensitive and it can consist of letters, numbers, periods, and underscores or combination of these. A simple program demonstrating the use of variable in R is:
var1 <- 5
var1
var2 <- "Hello Hive!"
var2
This program will give the following output.
In R unlike other programming languages like Java and C, you don't need to declare the variable. The value is assigned the moment you run the code. There are some naming conventions that you need to keep in mind if you want your program to be more readable. If you are using two words to represent a variable, it's good to do it by using underscore() between them (for example: first_name). It's a good practice to always start the variable name with lowercase letter. And it is also the best practice to avoid using the name of function or reserved words like TRUE, FALSE in order to avoid any confusion. Its a bad practice to start variable name with dot(.) or underscore().
Now we will briefly go over the data types used in R which are: numeric, integer, logical, character and complex data types. A simple example showcasing each data-type is shown in the following code:
# Numeric
x <- 56
typeof(x)
# Integer
y <- 56L
typeof(y)
# Logical
bool_1 <- FALSE
typeof(bool_1)
# Character
z <- "Hello World"
typeof(z)
# Complex
a <- 5 + 6i
typeof(a)
This code will give output as following: