R | Variable Conversion

The “as….” explicitly converts the data to whatever you desired outcome.

  • as.array(x)
  • as.data.frame(x)
  • as.numeric(x)
  • as.logical(x)
  • as.vector(x)
  • as.matrix(x)
  • as.complex(x)
  • as.character(x)
  • … convert type; for a complete list, use methods(as)
to one long
vector
to
matrix
to
data frame
from
vector
c(x,y) cbind(x,y)
rbind(x,y)
data.frame(x,y)
from
matrix
as.vector(mymatrix) as.data.frame(mymatrix)
from
data frame
as.matrix(myframe)

If you are interested in testing data types use “is…” instead of “as…” this will allow R to return a TRUE or FALSE outcomes.

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