An R Introduction to Statistics

Integer

In order to create an integer variable in R, we invoke the integer function. We can be assured that y is indeed an integer by applying the is.integer function.

> y = as.integer(3) 
> y              # print the value of y 
[1] 3 
> class(y)       # print the class name of y 
[1] "integer" 
> is.integer(y)  # is y an integer? 
[1] TRUE

We can also declare an integer by appending an L suffix.

> y = 3L 
> is.integer(y)  # is y an integer? 
[1] TRUE

Incidentally, we can coerce a numeric value into an integer with the as.integer function.

> as.integer(3.14)    # coerce a numeric value 
[1] 3

And we can parse a string for decimal values in much the same way.

> as.integer("5.27")  # coerce a decimal string 
[1] 5

On the other hand, it is erroneous trying to parse a non-decimal string.

> as.integer("Joe")   # coerce an non-decimal string 
[1] NA 
Warning message: 
NAs introduced by coercion

Often, it is useful to perform arithmetic on logical values. Just like the C language, TRUE has the value 1, while FALSE has value 0.

> as.integer(TRUE)    # the numeric value of TRUE 
[1] 1 
> as.integer(FALSE)   # the numeric value of FALSE 
[1] 0