Explicit Coercion

Objects can be explicitly coerced from one class to another. See the below examples.

 

x<- 1:10
class(x)
as.numeric(x)
as.logical(x)
as.character(x)

Output:

> x<- 1:10
> class(x)
[1] “integer”
> as.numeric(x)
[1] 1 2 3 4 5 6 7 8 9 10
> as.logical(x)
[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
> as.character(x)
[1] “1” “2” “3” “4” “5” “6” “7” “8” “9” “10”

Sometimes, R also don’t how to coerce an object and this can result in NAs being produced.

 

x <- c("Statistics", "R Programming", "Python")
as.numeric(x)
as.logical(x)

Output:

>as.numeric(x)
[1] NA NA NA
Warning message:
NAs introduced by coercion
> as.logical(x)
[1] NA NA NA

Frequently you may wish to create a vector based on a sequence of numbers. The quickest and easiest way to do this is with the : operator, which creates a sequence of integers between two specified integers.

 

y<-1:10
print(y)

Output:

> print(y)
[1] 1 2 3 4 5 6 7 8 9 10

If we want to create a sequence that isn’t limited to integers and increasing by 2 at a time, we can use the seq() function.

 

seq(from = 1, to = 10, by = 2)
seq(1.5, 10.2, 2)

Output:

[1] 1.5 3.5 5.5 7.5 9.5

Another common operation to create a vector is rep(), which can repeat a single value a number of times.

 

rep("Statistics", times = 10)
x<-c("Statistics","R Programming","Python")
rep(x, times = 3)
length(x)

Output:

[1] "Statistics" "Statistics" "Statistics" "Statistics" "Statistics" "Statistics" "Statistics" "Statistics" "Statistics"
[10] "Statistics"
>
> x<-c("Statistics","R Programming","Python")
> rep(x, times = 3)
[1] "Statistics" "R Programming" "Python" "Statistics" "R Programming" "Python" "Statistics" "R Programming"
[9] "Python"
> length(x)
[1] 3

Mixing Objects

Lists