Chapter 1 Data in R

Reference : R for Beginners.

1.1 Data Type

R has 6 data types.

  • logical
  • integer
  • numeric (double)
  • complex
  • character
  • (null)

R will save data when you assign it to the variable. With n <- 15, n is set to numeric,

## [1] "numeric"

We can use various operations(methods) with numeric type variables. For example,

## [1] 19
## [1] 45
## [1] 225
## [1] 2.142857
## [1] Inf

Note also that we can get access to stored data 15 by the variable name n. In addition, we can coerce the object n to be a integer type variable.

## [1] "integer"

By enclosing a string with double quotes, we create a character type object,

## [1] "character"
## Double quotes " " in double quotes

To define a logical object, we type

## [1] "logical"

R can interpret 0 as FALSE, other numbers as TRUE

## [1] TRUE
## [1] "logical"
## [1] FALSE
## [1] 2
## [1] "integer"

Google NaN NULL NA in R or type ?NA ?NaN ?NULL.

1.2 Data Structure

1.2.1 Vector

  • Define Vectors
##  [1] 0 0 0 0 0 0 0 0 0 0
## [1] "numeric"
## [1] 10
##  [1]  1  2  3  4  5  6  7  8  9 10
## [1] 1 3 5 7 9
## [1] 1 3 4 2
  • Manipulating Vectors
##  [1]  1  2  3  4  5  6  7  8  9 10
## [1]  2  6 10 14 18
##  [1]  2  3  4  5  6  7  8  9 10 11
##  [1]   1   4   9  16  25  36  49  64  81 100
##  [1] 1 3 5 7 9 0 0 0 0 0 0 0 0 0 0
## [1] 1
## [1] 1 7 3
## [1] 7 9
## [1] 1.666667
  • Note : Vector can contain only one type

1.2.2 Lists

Unlike vectors, lists can contain several data types.

## [1] 13
## [1] 13
## [1] "list"
## [[1]]
## [1] 1
## 
## [[2]]
## [1] 3
## 
## [[3]]
## [1] "2"
## $A
## [1] 1
## 
## $B
## [1] 3
## 
## $C
## [1] "2"
## List of 3
##  $ A: num 1
##  $ B: num 3
##  $ C: chr "2"

1.2.3 Matrix

  • Define Matrix
## [1] "matrix"
## [1] 2 4
##  logi [1:2, 1:4] NA NA NA NA NA NA ...
## $dim
## [1] 2 4
  • Assign elements of a matrix
##      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,]    1    3    5    7    9   11   13   15
## [2,]    2    4    6    8   10   12   14   16
##      [,1] [,2] [,3] [,4]
## [1,]    1    5    9   13
## [2,]    2    6   10   14
## [3,]    3    7   11   15
## [4,]    4    8   12   16
##      [,1] [,2] [,3] [,4]
## [1,]   15    3   -9  -21
## [2,]   12    0  -12  -24
## [3,]    9   -3  -15  -27
## [4,]    6   -6  -18  -30
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    0    0
## [2,]    0    1    0    0
## [3,]    0    0    1    0
## [4,]    0    0    0    1
##      [,1] [,2] [,3] [,4]
## [1,]    1    0    0    0
## [2,]    0    2    0    0
## [3,]    0    0    3    0
## [4,]    0    0    0    4
## [1]  15   0 -15 -30
  • Elementwise operations
  • Examples of built-in matrix operations

Google Array, Factor, DataFrame in R or type ?array ?factor ?data.frame.