What is the as.vector() function in R?
Overview
The as.vector() function in R is used to convert a matrix object into a non-distributed vector object.
Syntax
as.vector(x, mode = "any", proc.dest = "all")
Parameters
The as.vector() function takes the following parameter values:
x: Represents the numeric distributed matrix.mode: Represents a character string that gives an atomic mode or"list", or (except for vector)"any". It’s optional.proc.dest: Represents the destination process with which the matrix is stored. It’s optional.
Return value
The as.vector() function returns a vector object.
Code
Let’s look at the code below:
# create a matrix of stringsmymatrix <- matrix(c(1,2,3,4,5,6),nrow = 2,ncol = 2,byrow = FALSE,dimname = list(c("row1", "row2"),c("Col1", "Col2")))# printing the matrixmymatrix# implementing the as.vector() functionmyvector = as.vector(mymatrix)# printing the new vector objectmyvector# checking if its actually a vector objectis.vector(myvector)
Explanation
- Line 2: We create a matrix variable
mymatrixhaving2rows and2columns using thematrix()function. - Line 13: We print the matrix,
mymatrix. - Line 16: We implement the
as.vector()function to the matrix,mymatrix. The result is assigned to another variablemyvector. - Line 19: We print the vector object
myvector. - Line 22: We use the
is.vector()to check if the object,myvector, is a vector object.