R Objects: Data Types

  • OBJECTS
  • R has five basic classes of objects:
  1. Character
  2. Numeric
  3. Integer
  4. Complex
  5. Logical

However, the most basic object is a vector.

  • There are two things which you should remember when dealing with vectors.
    1. A vector can only contain objects of the same class.
    2. AND there is an exception to this, a list. A list looks like a vector, but can have different classes.

To create an empty vector use the following function:

vector()
Vectors can be created by using the following:
c() # used to concatenate individual values together
: # to create a sequence, such as 1:10
seq() # to create more complex sequences
rep() # replicates values
sort() # ordering elements in a vector
order() # ordering elements in a vector

 

An example of using rep()

rep(5,2) #a vector of two fives
[1] 5 5

 

An example of using c()

c(3,2,1) # vector of three numeric elements in that order
[1] 3 2 1

 

An example of using seq()

seq(4,20, by = 2)
[1]  4  6  8 10 12 14 16 18 20
seq(1,length = 20, by =4)
 [1]  1  5  9 13 17 21 25 29 33 37 41 45 49 53 57 61 65 69 73 77

R: Numbers

In general, numbers in R are treated as numeric objects.

For example,

 3 # numeric object
[1] 3
 3L # explicitly gives an integer
[1] 3
 Inf # a special number which represents infinity
[1] Inf
 1/0
[1] Inf
 1/Inf # can be used in calculations
[1] 0
 0/0 # NaN ("not a number"); also, seen as a missing number
[1] NaN

 

Numerics are also decimal values in R. This happens by default, so that if you create a decimal value for x that is will be of the numeric type.

 x = 8.3 # create x which a decimal value
 x # print the value of x
[1] 8.3
 class(x) # what is the class of x?
[1] "numeric"

 

Even when assigning an integer to a variable such as N, it is still being retained as a numeric value.

 N = 43
 N #print the value of N
[1] 43
 class(N) # what is the class of N?
[1] "numeric"

 

You can further confirm that N is not an integer by using the is.integer function.

 is.integer(N) # is N an integer?
[1] FALSE
 is.numeric(N) # is N numeric?
[1] TRUE