15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Convert Data Frame Column to Vector in R

How to Convert Data Frame Column to Vector in R

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

#use $ operator
new_vector #use indexing
new_vector column_name']]

#use 'pull' from dplyr package
new_vector 

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 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 
#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 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 
#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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories