2.1 Data Type
There are five basic data types:
- logical
- integer
- numeric
- complex
- character.
2.1.1 Logical
Logical data type is binary : it is either TRUE or FALSE.
x <- TRUE
x
## [1] TRUE
y <- FALSE
y
## [1] FALSE
TRUE and FALSE correspond to integer 0 and 1. And we can use it for calculation. Say \(x+x+x\) should give us 3:
x + x + x
## [1] 3
And \(x \times y\) should give us zero:
x * y
## [1] 0
One important logical data besides TRUE and FALSE is NA. It is usually used to denote missing data. One intesting feasture of NA is that any operation on it will give you the same result.
x <- NA
x + x
## [1] NA
x * x
## [1] NA
As we shall see in the next chapter, NA can be a problem because TRUE and FALSE is needed for conditional statement (e.g., if-statement).
To see what datat type of a variable is, we can use the function class().
class(x)
## [1] "logical"
2.1.2 Integer
Integer data type covers all whole numbers. It is represented by number and letter L: 1L, 2L, 3L.
x <- 1L
x
## [1] 1
class(x)
## [1] "integer"
2.1.3 Numeric
Numeric data type covers all real numbers.
x <- 2.6
x
## [1] 2.6
class(x)
## [1] "numeric"
2.1.4 Complex
Complex data type covers all complex numbers but this is rarely used in financial analysis.
x <- 2 +5i
x
## [1] 2+5i
class(x)
## [1] "complex"
2.1.5 Character
Character data type covers all text strings.
x <- "Hello World"
x
## [1] "Hello World"
class(x)
## [1] "character"