How to Convert Data Frame Column to Vector in R


You can use one of the following three methods to convert a data frame column to a vector in R:

#use $ operator
new_vector <- df$column_name

#use indexing
new_vector <- df[['column_name']]

#use 'pull' from dplyr package
new_vector <- dplyr::pull(df, column_name)

Each of these methods returns identical results.

The following examples show how to use each of these methods in practice with the following data frame:

#create data frame
df <- data.frame(a=c(1, 2, 5, 6, 12, 14),
                 b=c(8, 8, 9, 14, 22, 19),
                 c=c(3, 3, 2, 1, 2, 10))

#display data frame
df

   a  b  c
1  1  8  3
2  2  8  3
3  5  9  2
4  6 14  1
5 12 22  2
6 14 19 10

Example 1: Use $ Operator

The following code shows how to use the $ operator to convert a data frame column to a vector:

#convert column 'a' to vector
new_vector <- df$a

#view vector
new_vector

[1]  1  2  5  6 12 14

#view class of vector
class(new_vector)

[1] "numeric"

Example 2: Use Indexing

The following code shows how to use indexing to convert a data frame column to a vector:

#convert column 'a' to vector
new_vector <- df[['a']]

#view vector
new_vector

[1]  1  2  5  6 12 14

#view class of vector
class(new_vector)

[1] "numeric"

Example 3: Use ‘pull’ from dplyr

The following code shows how to use the ‘pull’ function from the dplyr package to convert a data frame column to a vector:

library(dplyr)

#convert column 'a' to vector
new_vector <- pull(df, a)

#view vector
new_vector

[1]  1  2  5  6 12 14

#view class of vector
class(new_vector)

[1] "numeric"

Notice that all three methods return identical results.

Note: If you happen to be working with an extremely large dataset, the ‘pull’ function from the dplyr package will perform the fastest out of the three functions shared in this tutorial.

Additional Resources

How to Convert Matrix to Vector in R
How to Convert a List to a Data Frame in R
How to Convert Character to Numeric in R

Leave a Reply

Your email address will not be published.