R Basic

What is as.vector() Function in R

The as.vector() function converts an input R object into a vector. The object can be anything like a matrix, array, or factor. The return value is a vector.

When you convert the matrix to a vector, it will remove the attributes, such as dimension, to transform into a vector.

When you convert a factor to a vector, it will remove the attribute, such as level, to transform it into a vector.

It does not always perform as expected when converting a list with elements of different types to a vector. Instead, you can use the unlist() is the standard and more appropriate function for converting a list to a vector.

Syntax

as.vector(obj, mode = "any", proc.dest = "all")

Parameters

Name Value
obj The object can be anything like matrices, arrays, or factors that will be converted into a one-dimensional vector format.
mode It is a character string giving an atomic mode or “list” or (except for ‘vector’) “any”.
proc.dest It is a destination process for storing the “matrix”.

Converting a matrix to a vector

mtrx <- matrix(c(1:9), 3, 3)
mtrx
class(mtrx)

vec <- as.vector(mtrx)
vec
class(vec)

Output

Converting an array to a vector

# Creating an array
arr <- array(c(1, 2, 3, 4), c(2, 2))
arr

# Calling as.vector() Function
cat("After converting an array to vector", "\n")
as.vector(arr)

Output

Converting a factor to a vector

You can use the as.vector() function to convert the factor into a character vector.

main_factor <- factor(c("apple", "banana", "apple", "orange"))

# Converting factor to vector
vec_factor <- as.vector(main_factor)

print(vec_factor) # "apple" "banana" "apple" "orange"
print(typeof(vec_factor)) # character

Checking if a variable is a vector

The is.vector() function checks if the input object is a vector.

mtrx <- matrix(c(1:9), 3, 3)

vec <- as.vector(mtrx)

is.vector(vec)

Output

[1] TRUE

That’s it.

Recent Posts

cbind() Function: Binding R Objects by Columns

R cbind (column bind) is a function that combines specified vectors, matrices, or data frames…

5 days ago

rbind() Function: Binding Rows in R

The rbind() function combines R objects, such as vectors, matrices, or data frames, by rows.…

5 days ago

as.numeric(): Converting to Numeric Values in R

The as.numeric() function in R converts valid non-numeric data into numeric data. What do I…

2 weeks ago

Calculating Natural Log using log() Function in R

The log() function calculates the natural logarithm (base e) of a numeric vector. By default,…

3 weeks ago

Dollar Sign ($ Operator) in R

In R, you can use the dollar sign ($ operator)  to access elements (columns) of…

1 month ago

Calculating Absolute Value using abs() Function in R

The abs() function calculates the absolute value of a numeric input, returning a non-negative (only…

1 month ago