Sunday 14 June 2015

R : Coercion

Implicit Coercion

When you tried to add different types of data elements to vector, then R convert them to lower of the given data types, to maintain same data type for all elements in vector.
> vector3 = c(1, 2, "3", 10.06, TRUE)
> 
> vector3
[1] "1"     "2"     "3"     "10.06" "TRUE" 
> 
> class(vector3)
[1] "character"

As you observe, vector3 has
 1, 2 and 10.06 are of type numeric
         “3” is of type character
         TRUE is of type logical
To satisfy vector property (All elements must of same data type), vector3 converted as character vector.

Explicit coercion

You can perform coercion explicitly by using the functions supplied by R language. Functions like as.numeric(),  as.character(), as.logical(), as.complex are used to perform explicit coercion.
> vector4 <- 1:6
> class(vector4)
[1] "integer"
> vector4
[1] 1 2 3 4 5 6
> 
> vector5 <- as.logical(vector4)
> vector5
[1] TRUE TRUE TRUE TRUE TRUE TRUE
> class(vector5)
[1] "logical"
> 
> vector6 <- as.character(vector4)
> vector6
[1] "1" "2" "3" "4" "5" "6"
> class(vector6)
[1] "character"
> 
> vector7 <- as.complex(vector4)
> vector7
[1] 1+0i 2+0i 3+0i 4+0i 5+0i 6+0i
> class(vector7)
[1] "complex"


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment