How to Test Vector Types in R - dummies

How to Test Vector Types in R

By Andrie de Vries, Joris Meys

R contains a set of functions that allow you to test for the type of a vector. All these functions have the same syntax: is, a dot, and then the name of the type.

You can test whether a vector is of type foo by using the function. This test works for every type of vector; just replace foo with the type you want to check.

To test whether baskets.of.Granny is a numeric vector, for example, use the following code:

> is.numeric(baskets.of.Granny)
[1] TRUE

You may think that baskets.of.Granny is a vector of integers, so check it, as follows:

> is.integer(baskets.of.Granny)

R disagrees with the math teacher here. Integer has a different meaning for R than it has for us. The result of is.integer() isn’t about the value but about the way the value is stored in memory.

R has two main modes for storing numbers. The standard mode is double. In this mode, every number uses 64 bits of memory. The number also is stored in three parts. One bit indicates the sign of the number, 52 bits represent the decimal part of the number, and the remaining bits represent the exponent.

This way, you can store numbers as big as 1.8 × 10308 in only 64 bits. The integer mode takes only 32 bits of memory, and the numbers are represented as binary integers in the memory. So, the largest integer is about 2.1 billion, or, more exactly, 231 – 1. That’s 31 bits to represent the number itself, 1 bit to represent the sign of the number, and –1 because you start at 0.

You should use integers if you want to do exact integer calculations on small integers or if you want to save memory. Otherwise, the mode double works just fine.

You force R to store a number as an integer by adding L after it, as in the following example:

> x <- c(4L,6L)
> is.integer(x)
[1] TRUE

Whatever mode is used to store the value, is.numeric() returns TRUE in both cases.