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.
as.vector(obj, mode = "any", proc.dest = "all")
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”. |
mtrx <- matrix(c(1:9), 3, 3)
mtrx
class(mtrx)
vec <- as.vector(mtrx)
vec
class(vec)
Output
# 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
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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
The scale() function in R centers (subtracting the mean) and/or scales (dividing by the standard…
To rename a file in R, you can use the file.rename() function. It renames a…
The prop.table() function in R calculates the proportion or relative frequency of values in a…
The exp() is a built-in function that calculates the exponential of its input, raising Euler's…
The split() function divides the input data into groups based on some criteria, typically specified…
The colMeans() function in R calculates the arithmetic mean of columns in a numeric matrix,…