R Data Frame – Select column by index

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

We shall cover scenarios where we 1. Select column with index=1 from Data Frame 2. Select column with index=2 from Data Frame using index of the column in Data Frame.

Please note that the index starts from 1 and increments in steps of one for the next columns. For the first column index=1, for the second column index=2, for the third column index=3, and so on.

1. Select column whose index=1 from Data Frame using index notation in R

We can select a column from Data Frame by its index. To select the first column of Data Frame, we have to use the index of the first column. The index of the first column is 1.

Use the following expression to select the first column of Data Frame df.

</>
Copy
df[,1]

The empty space before the comma specifies that we would like to select all the rows. And 1 specifies that we would like to select the column whose index=1.

Steps

  1. We are given a Data Frame in df.
  2. Select the first column in the Data Frame using the expression df[,1]. You may store it in a variable, column_1.

Program

R program to select column from Data Frame whose index=1 (first column) using index notation.

example.R

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

cat("Given Data Frame\n")
print(df)

# Select first column from the Data Frame
column_1 <- df[,0]

cat("\nFirst column\n")
print(column_1)

Output

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

First column
[1] "Foo" "Bar" "Moo"

2. Select column whose index=2 from Data Frame using index notation in R

In this example, we shall take the same Data Frame df as in the previous example, and select the second column. The index of second column is 2. Therefore, we shall use the following expression df[,2] to select the column with index=2.

example.R

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

cat("Given Data Frame\n")
print(df)

# Select column with index=2 from the Data Frame
column_1 <- df[,2]

cat("\nColumn with index=2\n")
print(column_1)

Output

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

Column with index=2
[1] 30 25 35

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. In the first example, we have seen how to select the column with index=1, and in the second example, we have seen how to select the column with index=2.