Convert dataframe column to vector in R
Last Updated :
21 Apr, 2021
In this article, we will discuss how to convert a DataFrame column to vector in R Programming Language. To extract a single vector from a data frame in R Programming language, as.vector() function can be used.
Syntax: as.vector( data_frame$column_name )
Here,
- data_frame is the name of the data frame
- column_name is the column to be extracted
Given below are some implementations for this.
Example 1:
R
std.data <- data.frame (std_id = c (1:5),
std_name = c ( "Ram" , "Shayam" , "Mohan" ,
"Kailash" , "Aditya" ),
marks = c (95,96,95,85,80)
)
name.vec <- as.vector (std.data$std_name)
print (name.vec)
|
Output:
[1] “Ram” “Shayam” “Mohan” “Kailash” “Aditya”
We can now examine whether the returned column is a vector or not, by passing it to the function is.vector() which returns a Boolean value i.e. either true or false.
Example 2:
We will extract the Species column from the well-known data frame Iris using as.vector( ) function and print it. We will also check whether the returned column is a vector or not.
R
df <- iris
head (df)
name.vec <- as.vector (df$Species)
print (name.vec)
is.vector (name.vec)
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...