Jeff Stevens

2023-02-03

# Data types

• Double

• Integer

• Character

• Logical

## Numeric data

### Doubles

#### Floating-point numbers with decimals

# assign value 7.2 to object a
(a <- 7.2) # remember, wrapping in parentheses prints to console
 7.2
typeof(a)
 "double"

## Numeric data

### Integers

#### Numbers without decimals

(b <- 7)
 7
typeof(b)
 "double"

Doubles can have 0 as decimal

## Numeric data

### Integers

#### Numbers without decimals (specified with L)

(c <- 7L)
 7
typeof(c)
 "integer"

## Character data

#### Must be surrounded by ""

(d <- "Hello, world")
 "Hello, world"
(e <- "7")
 "7"
typeof(e)
 "character"

## Let’s explore!

• Type b, c, and e into the console separately. What do you see?
• Add b + c.
• Add b + e.

## Logical

#### Logical operators: >, >=, <, <=, ==, !=, %in%

a
 7.2
a > 5
 TRUE
d
 "Hello, world"
(mytest <- d == "Good-bye, world")
 FALSE
typeof(mytest)
 "logical"

## Logical

#### The logical operator for equals is ==

Note

We use

• == for logical equals
• <- for assigning objects
• = for assigning function argument values to argument names

## Logical

#### %in% operator: “is contained in”

(subjects <- c("01", "02", "03", "04", "05"))
 "01" "02" "03" "04" "05"
"03" %in% subjects
 TRUE
"06" %in% subjects
 FALSE

#### Test “is NOT contained in” with ! before test string

!"06" %in% subjects
 TRUE

• Factors

• Dates

## Factors

#### Augmented integers with ‘levels’

(i <- factor("married", levels = c("single", "married", "widowed")))
 married
Levels: single married widowed
typeof(i)
 "integer"

Note

Use class() to view augmented data type

class(i)
 "factor"

## Dates

#### Augmented numerics based on number of days since 1970-01-01

(j <- as.Date("1970-01-01"))
 "1970-01-01"
typeof(j)
 "double"
class(j)
 "Date"

Note

Make sure to wrap dates in ""

## Dates

#### You can do math on dates

(k <- as.Date("2023-02-03"))
 "2023-02-03"
k-j
Time difference of 19391 days

## Check data types

• Check with typeof()/class()
• Check in RStudio
• Use is.<type>() functions:
is.logical(), is.numeric(), is.character()
is.character(7)
 FALSE
is.character("7")
 TRUE

## Converting between data types (coercion)

#### Use as.<type>() functions:

as.logical(), as.numeric(), as.character()

e
 "7"
typeof(e)
 "character"
(l <- as.numeric(e))
 7
typeof(l)
 "double"

## Converting between data types (coercion)

(m <- "TRUE")
 "TRUE"
typeof(m)
 "character"
(n <- as.logical(m))
 TRUE
typeof(n)
 "logical"

## Converting between data types (coercion)

#### Factors to numerics is tricky

(o <- factor(0, levels = c("1", "0")))
 0
Levels: 1 0
as.numeric(o)
 2

#### First coerce to character

as.character(o)
 "0"
as.numeric(as.character(o))
 0

## Special values

#### NA represents missing values

• Each data type has its own type of NA

• Check with is.na()

#### NaN means “not a number” (undefined)

• 0 / 0 = NaN

#### Inf and -Inf represent infinity and negative infinity

• 1 / 0 = Inf

• -1 / 0 = -Inf