Conversion Functions
Principle and Dedicated Functions
In some cases, an object can be converted into another type. These conversions (also known as coercion or cast) allow you to change the format of an object to pass it to a function that would otherwise not be compatible with its original format. The functions used for this purpose generally have the prefix “as.”. As you can see from the following command, there are many such functions.
Here are some examples:
as.factor()
: to convert to a factor.as.data.frame()
: to convert to a data.frame.as.matrix()
: to convert to a matrix.as.list()
: to convert to a list.as.numeric()
: to convert to a numeric vector.as.character()
: to convert to a character vector.
apropos("^as\\.")
Additionally, there are conversion functions that do not start with
the prefix “as.”, such as unlist()
, which transforms a list
into a vector.
my_list <- list(A=1:5, B=letters[1:5])
unlist(my_list)
Convert to Modify a Result
This exercise aims to demonstrate one of the key advantages of conversion. This is one of R’s strengths. Some functions are polymorphic, meaning their behavior depends on the type of argument provided to the function.
- Given the following matrix. Use the
boxplot()
function on the matrix and on the matrix converted to a vector (as.vector()
).
set.seed(456)
mat <- matrix(c(rnorm(n=20, mean=5, sd=2),
rnorm(n=20, mean=3, sd=1),
rnorm(n=20, mean=2, sd=2)),
ncol=3, byrow = FALSE)
boxplot(mat)
boxplot(as.vector(mat))
Given the same matrix, apply the
plot()
function on:- the matrix \(mat\) passed as the sole argument.
- the first column of \(mat\) passed as the sole argument (drop=TRUE).
- the first column of \(mat\) passed as the first argument and the second column of \(mat\) passed as the second argument.
plot(mat)
plot(mat[, 1])
plot(mat[, 1], mat[, 2])
End of the section
Thank you for following this tutorial.