Chapter 4 Data Types

4.1 Introduction

In this chapter, we will learn about the following data types:

  • numeric/double
  • integer
  • character
  • logical
  • date/time

4.2 Numeric

In R, numbers are represented by the data type numeric. We will first create a variable and assign it a value. Next we will learn a few methods of checking the type of the variable.

## [1] "numeric"
## [1] "numeric"
## [1] TRUE
## [1] TRUE

If you carefully observe, integers are also treated as numeric/double. We will learn to create integers in a while. In the meanwhile, we have introduced two new funtions in the above example:

  • class(): returns the class or type
  • is.numeric(): tests whether the variable is of type numeric

4.3 Integer

Unless specified otherwise, integers are treated as numeric or double. In this section, we will learn to create variables of the type integer and to convert other data types to integer.

  • create a variable number1 and assign it the value 3
  • check the data type of number1 using class
  • create a second variable number2 using as.integer and assign it the value 3
  • check the data type of number2 using class
  • finally use is.integer to check the data type of both number1 and number2
## [1] "numeric"
## [1] "integer"
## [1] FALSE
## [1] TRUE

4.4 Character

Letters, words and group of words are represented by the data type character. All data of type character must be enclosed in single or double quotation marks. In fact any value enclosed in quotes will be treated as character. Let us create two variables to store the first and last name of a some random guy.

## [1] "character"
## [1] "character"
## [1] TRUE
## [1] TRUE

You can coerce any data type to character using as.character().

## [1] "30"
## [1] "9.8"
## [1] "TRUE"
## [1] "2019-02-19 20:19:13"

4.5 Logical

Logical data types take only 2 values. Either TRUE or FALSE. Sich data types are created when we compare two objects in R using comparison or logical operators.

  • create two variables x and y
  • assign them the values TRUE and FALSE respectively
  • use is.logical to check data type
  • use as.logical to coerce other data types to logical
## [1] "logical"
## [1] TRUE

The outcome of comparison operators is always logical. In the below example, we compare two numbers to see the outcome.

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

TRUE is represented by all numbers except 0. FALSE is represented only by 0 and no other numbers.

## [1] TRUE
## [1] FALSE
## [1] 1
## [1] 0
## [1] TRUE

Use as.logical() to coerce other data types to logical.

## [1] TRUE
## [1] TRUE
## [1] TRUE
## [1] TRUE