class(4)
[1] "numeric"
We will use the tidyverse style guide for styling R code.
Some of the commonly used objects in R are numbers - integer and double (or numeric), character and logical (TRUE/FALSE). The data type of the object can be identified using the in-built R function class()
or typeof()
. For example, see the following objects and their types:
class(4)
[1] "numeric"
typeof(4)
[1] "double"
class(4.4)
[1] "numeric"
typeof(4.4)
[1] "double"
class(4L)
[1] "integer"
typeof(4L)
[1] "integer"
class('4')
[1] "character"
typeof('4')
[1] "character"
class(TRUE)
[1] "logical"
typeof(FALSE)
[1] "logical"
We have the following rules for a R variable name:
Sometimes a value may have a datatype that is not suitable for using it. For example, consider the variable called annual_income
in the code below:
= "80000" annual_income
Suppose we wish to divide annual_income
by 12 to get the monthly income. We cannot use the variable annual_income
directly as its datatype is a string and not a number. Thus, numerical operations cannot be performed on the variable annual_income
.
We’ll need to convert annual_income to an integer. For that we will use the R’s in-built as.integer() function:
= as.integer(annual_income)
annual_income = annual_income/12
monthly_income print(paste0("monthly income = ", monthly_income))
[1] "monthly income = 6666.66666666667"
Similarly, datatypes can be converted from one type to another using in-built R functions as shown below:
#Converting integer to character
as.character(9)
[1] "9"
#Converting character to numeric
as.numeric('9.4')
[1] 9.4
#Converting logical to integer
as.numeric(FALSE)
[1] 0
Note that any non-zero numeric value, if converted to the ‘logical’ datatype, will return TRUE
, while converting 0 to the ‘logical’ datatype will return FALSE
. Only numeric values can be converted to the ‘logical’ datatype.
# Converting integer to logical
as.logical(40)
[1] TRUE
# Converting integer to logical
as.logical(0)
[1] FALSE
# Converting integer to logical
as.logical(-30.1)
[1] TRUE
Sometimes, conversion of a value may not be possible. For example, it is not possible to convert the variable greeting defined below to a number:
= "hello" greeting
However, strings can be concatenated using the paste0()
function:
paste0("hello", " there!")
[1] "hello there!"
R’s in-built readline() function can be used to accept an input from the user. For example, suppose we wish the user to input their age:
= readline("Enter your age:") age
Enter your age:
The entered value is stored in the variable age
and can be used for computation.