In this tutorial, we will look at how to convert a column in an R dataframe to a vector with the help of some examples.

## How do you get column values as a vector in R?

You can use the `[[]]`

notation to get an R dataframe’s column values as a vector using the column name or the column index.

The following is the syntax –

dataframe[[columan_name]]

We get the column values as a vector.

## Steps to convert R dataframe column to a vector

Let’s now look at the steps to follow to get a column’s values as a vector in an R dataframe.

### Step 1 – Create a dataframe

First, we will create a dataframe that we will be using throughout this tutorial.

# create a dataframe employees_df = data.frame( "Name"= c("Jim", "Dwight", "Angela", "Tobi", "Kevin"), "Age"= c(26, 28, 29, 32, 30), "Department"= c("Sales", "Sales", "Accounting", "HR", "Accounting") ) # display the dataframe print(employees_df)

Output:

Name Age Department 1 Jim 26 Sales 2 Dwight 28 Sales 3 Angela 29 Accounting 4 Tobi 32 HR 5 Kevin 30 Accounting

We now have a dataframe containing information about some employees working in an office. The dataframe has columns “Name”, “Age”, and “Department”.

Note that we use vectors here as column values to create a dataframe. You can think of a dataframe as vertical column vectors stacked side-by-side to form a tabular structure.

### Step 2 – Get column value as a vector using `[[]]`

notation

The values in a column are represented by a vector. Thus to get the vector of values for a column, we just need to access the column values which we can do using the `[[]]`

notation.

Let’s now get the values in the “Name” column as a vector. For this, we’ll access the column values using the column name “Name”.

# get column "Name" values names <- employees_df[["Name"]] # display the vector print(names)

Output:

[1] "Jim" "Dwight" "Angela" "Tobi" "Kevin"

We get a vector of values from the “Name” column.

Note that you can also use the column index to access a column’s values. For example, in the above dataframe, the index of the “Name” column is 1 (rows and columns in R are indexed starting from 1).

# get column "Name" values names <- employees_df[[1]] # display the vector print(names)

Output:

[1] "Jim" "Dwight" "Angela" "Tobi" "Kevin"

We get the same result as above.

You might also be interested in –

- Create a DataFrame in R
- How to Add a Row to a Dataframe in R?
- How to Add a Column to a Dataframe in R?

**Subscribe to our newsletter for more informative guides and tutorials. ****We do not spam and you can opt out any time.**