Convert Data Frame Column to Vector in R (3 Examples)

 

In this article you’ll learn how to convert a data frame column to a vector in R programming.

The tutorial contains three examples for the conversion of data frame columns. To be more precise, the tutorial contains this:

Let’s start right away:

 

Creation of Example Data

We’ll use the following data frame as example data for this tutorial:

data <- data.frame(x1 = 1:5,            # Create example data
                   x2 = letters[1:5])
data                                    # Print example data
# x1 x2
#  1  a
#  2  b
#  3  c
#  4  d
#  5  e

Our data frame contains two variables: x1 and x2. Now, let’s assume that we want to convert the column x1 to a vector object in R…

 

Example 1: Convert Data Frame Column to Vector with $-Operator

The first example shows how to extract a variable from a data frame with the $-operator:

vec1 <- data$x1                         # $-Operator
vec1
# 1 2 3 4 5

As you can see based on the output of the RStudio console, we stored the values of the column x1 in the vector object vec.

This is probably the easiest solution, in case you want to convert a data frame column to a vector in R. However, there are several other alternatives…

 

Example 2: Convert Data Frame Column to Vector by Subsetting Data

In Example 2, we’ll take a subset of exactly one column from our data frame:

vec2 <- data[ , "x1"]                   # Subsetting column
vec2
# 1 2 3 4 5

The output is exactly the same as in Example 1.

 

Example 3: Convert Data Frame Column to Vector with pull Function [dplyr Package]

Another way for the conversion of a variable to a vector is provided by the dplyr R package. Let’s install and load the package:

install.packages("dplyr")               # Install dplyr
library("dplyr")                        # Load dplyr

Now, we can use the pull function of the dplyr package as follows:

vec3 <- pull(data, x1)                  # pull function
vec3
# 1 2 3 4 5

Again, the same output.

 

Video, Further Resources & Summary

Do you want to learn more about converting data frame columns in R? Then you might watch the following video of my YouTube channel. In the video, I show the R programming syntax of this tutorial.

 

The YouTube video will be added soon.

 

Furthermore, you might have a look at the related tutorials on statisticsglobe.com. You can find some articles about data conversion and related topics below.

 

In this R tutorial you learned how to use a data frame column as vector. Don’t hesitate to let me know in the comments section, in case you have further comments or questions.

 



Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top