R: Data Type of a Variable

In Programming Language, we need to use various variables to store various information.

In R the variables are not declared as some data types. These variables are directly assigned to R-Objects and the data type of the R-object becomes the data type of the variable. Here are some frequently used R-Objects.

1. Vector: 

It is the basic data type for R-Objects. It has 6 Atomic Vector which are:

  1. Integer
  2. Logical
  3. Double
  4. Complex
  5. Character 
  6. Raw

As vector hold elements of different classes so to create vector with more than one elements we use c() function which means to combine the elements into a vector.

Example:

a <- c(2,4,5.4,6,-2,-4) 
b <- c("one","two","three","four")
print(class(2))
print(class("one"))

Output:

[1] "character"
[1] "numeric"

2. Lists:

It is an ordered collection of lists. It is basically similar to Vector. It can also store different types of elements.

Example:

> list1<-list(c(2,4),5,6.8,7,cos)
> print(list1)

Output:

[[1]]
[1] 2 4

[[2]]
[1] 5

[[3]]
[1] 6.8

[[4]]
[1] 7

[[5]]
function (x)  .Primitive("cos")

3. Matrices:

 It can be easily created by using vectors input to the matrix function.

Example:

a<-matrix(1:12,nrow=3 ,ncol=4)
print(a)

Output:

     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

4. Arrays:

It is similar to the matrix but matrices are only confined to 2-d, an array can have any number of dimensions.

Example:

a<-array(c(1,2,3) ,dim=c(3,2,2))
print(a)

Output:

, , 1

     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3

, , 2

     [,1] [,2]
[1,]    1    1
[2,]    2    2
[3,]    3    3

4. Data Frame

In the data frame, different columns have different modes. Suppose if the first column is numerical then the second column can be logical third column can be a character.

Examples:

> School<-data.frame(
      name = c("Arjun", "Khushi","Shreya"), 
      Roll_no= c(10, 15, 30), 
      marks_1= c(80,70,85),
      marks_2= c(42,38,26)
  )
> print(School)
 

Output:

    name Roll_no marks_1 marks_2
1  Arjun      10      80      42
2 Khushi      15      70      38
3 Shreya      30      85      26

5. Factors:

It is created using vectors. It is very useful for the purpose of statistical modeling. It stores vector values that are labeled with distinct values. These labels can be anything like characters irrespective of whether it is numeric or character or boolean etc. in the input vector. 

Examples:

> students<-c("Arjun","Khushi","Shreya")
> factor_student<-factor(students)
> print(factor_student)

Output:

[1] Arjun  Khushi Shreya
Levels: Arjun Khushi Shreya