R Data Types


Like most scripting languages, variables in R are not hard typed. You do not declare a variable to be limited to a given data type. The variables in R are assigned with R-Objects and the data type of the R-object becomes the data type of the variable. There are many types of R-objects. The frequently used ones are:

  • Vectors
  • Lists
  • Matrices
  • Arrays
  • Factors
  • Data Frames

The simplest of these objects is the vector object and there are six data types of these atomic vectors, also termed as six classes of vectors. The other R-Objects are built upon the atomic vectors.

  • Logical (TRUE / FALSE)
  • Numeric (1, 2, 33.44)
  • Integer (1L, -100L, 0L
  • Complex (4 + 10i))
  • Character ("1", "examples", 'of', "characters")
  • Raw (A raw sequence of bytes.)
v <- TRUE 
print(class(v))
[1] "logical" 

v <- 23.5
print(class(v))
[1] "numeric"

v <- 2L
print(class(v))
[1] "integer"

v <- 2+5i
print(class(v))
[1] "complex"

v <- "TRUE"
print(class(v))
[1] "character"

v <- charToRaw("Convert Characters to RAW")
print(class(v))
[1] "raw"

Variable


A valid variable name consists of letters, numbers and the dot or underline characters. The variable name starts with a letter or the dot not followed by a number.

var_name2. # Valid Has letters, numbers, dot and underscore
var_name% # Invalid Has the character '%'. Only dot(.) and underscore allowed.
2var_name # Invalid Starts with a number
.var_name # Valid Can start with a dot(.) but the dot(.)should not be followed by a number.
var.name # Valid Variable name can contain a dot(.)
.2var_name # Invalid The starting dot is followed by a number making it invalid.
_var_name # Invalid Starts with _ which is not valid

The variables can be assigned values using leftward, rightward and equal to operator.

# Assignment using equal operator.
var.1 = c(0,1,2,3)

# Assignment using leftward operator.
var.2 <- c("learn","R")

# Assignment using rightward operator.   
c(TRUE,1) -> var.3

cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")

print() / cat()


We can view the contents of a variable using the print or cat functions. Print takes a single parameter while cat takes multiple parameters and concatenates them all.

print("Hello World")
[1] "Hello World"

cat("Hello", "World")
Hello world

ls() / rm()


R does not provide for namespaces. (You can import certain packages to enforce namespaces). For example, a variable declared in an if block is also available after you come out of the block. It is very easy to lose track of the variables available at a given point. R provides for two very useful functions to deal with this.

ls() gives a list of variables defined at a given time. And, if you want, you can also delete a variable from the memory using the rm()