Convert Data Frame Row to Vector in R (Example)

 

In this article, I’ll illustrate how to extract a row from a data frame and convert it to a vector in the R programming language.

Table of contents:

So now the part you have been waiting for – the programming part:

 

Creation of Example Data

First, we have to create some example data in R:

data <- data.frame(x1 = 1:5,      # Create example data
                   x2 = 2:6,
                   x3 = 3:7)
data                              # Print example data
#   x1 x2 x3
# 1  1  2  3
# 2  2  3  4
# 3  3  4  5
# 4  4  5  6
# 5  5  6  7

Our data frame consists of five rows and three columns. Note that all columns have the same data type (i.e. numeric).

 

Example: Convert Row to Numeric Vector

If we want to extract a particular row of our data frame, we can specify the row index of this row within square brackets:

data[3, ]                         # Extract row of data frame
#   x1 x2 x3
# 3  3  4  5

As you can see based on the previous output of the RStudio console, we have just extracted a single row from our data matrix. However, this output is still a one-row data frame.

In order to convert this one-row data frame to a vector, we can use the as.numeric function as follows:

as.numeric(data[3, ])             # Convert row to vector
# 3 4 5

The final output is a numeric vector consisting of the values of row three.

 

Video & Further Resources

I have recently published a video on my YouTube channel, which illustrates the topics of this page. You can find the video below.

 

The YouTube video will be added soon.

 

In addition, I can recommend to read the other articles of https://statisticsglobe.com/. You can find a selection of tutorials below:

 

In summary: You learned in this article how to convert a row of a data frame to a vector (or array) in R. In case you have additional questions, let me know in the comments.

 



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