The Wayback Machine - https://web.archive.org/web/20231205221509/https://www.geeksforgeeks.org/convert-dataframe-column-to-vector-in-r/
Open In App
Related Articles

Convert dataframe column to vector in R

Improve Article
Improve
Save Article
Save
Like Article
Like

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




# creating dataframe 
std.data <- data.frame(std_id = c (1:5), 
                       std_name = c("Ram","Shayam","Mohan",
                                    "Kailash","Aditya"),
                       marks = c(95,96,95,85,80)
                      )
  
# extracting vector from
# dataframe column std_name
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
  
# print the data frame
head(df)
  
# extracting vector from
# dataframe column Species
name.vec <- as.vector(df$Species)
  
print(name.vec)
  
# returns Boolean value
is.vector(name.vec) 


Output:


Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Apr, 2021
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials