R Data Frame – Select first column

To select the first column in a Data Frame, you can select the column by index, or select the column by name.

In this tutorial, you will learn how to select the first column in a Data Frame in R language, and cover examples with the approaches using index or column name.

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

The index starts from 1 and increments in steps of one for the columns in a data frame. For the first column index=1.

To select the first column of Data Frame df using index, we have to use the following expression.

</>
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, which is our first column.

The following is the R program to select the first column from Data Frame using index.

example.R

</>
Copy
# 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 first column
first_column <- df[,1]

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

Output

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

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

2. Select first column from Data Frame using column name in R

If you know the name of first column in Data Frame, you can use the column name instead of the index.

To select the first column of Data Frame df using column name, we have to use the following expression.

</>
Copy
df[,first_column_name]

In the data frame we have taken, the name of the first column is "name". Therefore, we shall use this in the above expression to get the first column.

The following is the R program to select the first column from the Data Frame df using column name.

example.R

</>
Copy
# 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 first column
first_column <- df[,"name"]

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

Output

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

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

Summary

In this tutorial, we learned how to select the first column 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 first column using index, and in the second example, we have seen how to select the first column using column name.

The first approach using index is recommended. The second approach is only for demonstrating another possibility.