Types

Types

Every vector has a type. R has six basic (“atomic”) types, and you will use four of them regularly:

Type Examples Notes
double 3.2, -1, 1e6 R’s usual type for numbers (“numeric”)
integer 5L, 1:10 the L marks an integer
character "Durham", "1" text, always in quotes
logical TRUE, FALSE all capitals (Python writes True)

The other two, complex and raw, you are unlikely to need.

typeof() tells you the type of a vector. Because a vector holds one type only, combining different types makes R coerce everything to the most flexible type: c(1, "a", TRUE) becomes a character vector. This causes a familiar surprise with real data, where one stray bit of text in a column of numbers makes R read the whole column as character.

Missing values are written NA, whatever the type.

Run the chunk below and predict each answer before you look.

Atomic types

Which of these is not an atomic data type?








What type?

What type of data is "1L"?





Integers

Create a vector of integers from one to five. Can you imagine why you might want to use integers instead of numbers/doubles?

c(1L, 2L, 3L, 4L, 5L)

Floating point arithmetic

Computers must use a finite amount of memory to store decimal numbers (which can sometimes require infinite precision). As a result, some decimals can only be saved as very precise approximations. From time to time you’ll notice side effects of this imprecision, like below.

Compute the square root of two, square the answer (e.g. multiply the square root of two by the square root of two), and then subtract two from the result. What answer do you expect? What answer do you get?

sqrt(2) * sqrt(2) - 2
sqrt(2)^2 - 2

Vectors

How many types of data can you put into a single vector?




Character or object?

One of the most common mistakes in R is to call an object when you mean to call a character string and vice versa.

Which of these are object names? What is the difference between object names and character strings?







Next topic