R Data Frame – Select column by name

In this tutorial, you will learn how to select a column from a Data Frame by its name in R language.

To select a column by name from a Data Frame df, you can use the index notation as shown in the following.

df[,column_name]

where column_name is the name of the column which we would like to select. And the empty space before the comma specifies that we would like to select all the rows.

1. Select column with specified column name from Data Frame using index notation in R

In this example, we are given a Data Frame df with three columns whose names are "name", "age", and "place" to store the data of people. We have to select the column whose name is "name" to get the names of people in the data frame df.

Use the following expression to select the column with the column name "name" from the Data Frame df.

df[,"name"]

The following is the R program to select column from Data Frame whose name is "name" using index notation.

example.R

# Given a DataFrame
df <- data.frame(name = c("Foo", "Bar", "Moo"),
                 age = c(30, 25, 35),
                 city = c("X", "Y", "Z"))

cat("Given DataFrame\n")
print(df)

# Select column whose name is "name"
selected_column <- df[,"name"]

cat("\nSelected column \"name\"\n")
print(selected_column)

Output

Given DataFrame
  name age city
1  Foo  30    X
2  Bar  25    Y
3  Moo  35    Z

Selected column "name"
[1] "Foo" "Bar" "Moo"

2. Select column whose name is “city” from Data Frame in R

In this example, we shall take the same Data Frame df as in the previous example, and select the column whose column name is "place". All we have to do is replace the column_name with "city" in the expression df[,column_name].

example.R

# Given a DataFrame
df <- data.frame(name = c("Foo", "Bar", "Moo"),
                 age = c(30, 25, 35),
                 city = c("X", "Y", "Z"))

cat("Given DataFrame\n")
print(df)

# Select column "city"
selected_column <- df[,"city"]

cat("\nSelected column \"city\"\n")
print(selected_column)

Output

Given DataFrame
  name age city
1  Foo  30    X
2  Bar  25    Y
3  Moo  35    Z

Selected column "city"
[1] "X" "Y" "Z"

Summary

In this tutorial, we learned how to select a column by index from a given Data Frame in R language.

We have covered two examples. We have taken a data frame with three columns, and in the first example, we have seen how to select the column with the column name "name", and in the second example, we have seen how to select the column with column name "city".