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 strings
mymatrix <- matrix(
c(1,2,3,4,5,6),
nrow = 2,
ncol = 2,
byrow = FALSE,
dimname = list(
c("row1", "row2"),
c("Col1", "Col2")
)
)
# printing the matrix
mymatrix
# implementing the as.vector() function
myvector = as.vector(mymatrix)
# printing the new vector object
myvector
# checking if its actually a vector object
is.vector(myvector)

Explanation

  • Line 2: We create a matrix variable mymatrix having 2 rows and 2 columns using the matrix() 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 variable myvector.
  • 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.

Free Resources