Select Columns from Data Frame
We can select columns from a data frame in R, either by using indices or names of the columns.
To select one or more columns from a data frame by indices, pass the indices of columns as a vector to the data frame indexing, as shown in the following.
data_frame_name[, c(index_1, index_2, index_3)]
To select one or more columns from a data frame by column names, pass the names of columns as a vector to the data frame indexing, as shown in the following.
data_frame_name[, c('column_name_1', 'column_name_2')]
In both the above referencing techniques, the expression returns a new data frame with the specified columns.
Examples
Select Columns of Data Frame by Index
In the following example, we take a data frame in df
, with three columns, and then select the first (index = 1), and third (index = 3) columns.
example.r
df <- data.frame(name = c("A", "B", "C", "D"),
age = c(4, 8, 10, 14),
income = c(1.6, 1.5, 1.7, 1.9))
result <- df[, c(1, 2)]
print(result)
Output
tutorialkart$ Rscript example.r
name age
1 A 4
2 B 8
3 C 10
4 D 14
Select Columns of Data Frame by Name
In the following example, we take a data frame in df
, with three columns, and then select the columns with the names: c(name, income)
.
example.r
df <- data.frame(name = c('A', 'B', 'C', 'D'),
age = c(4, 8, 10, 14),
income = c(1.6, 1.5, 1.7, 1.9))
result <- df[, c('name', 'income')]
print(result)
Output
tutorialkart$ Rscript example.r
name income
1 A 1.6
2 B 1.5
3 C 1.7
4 D 1.9
Conclusion
In this R Tutorial, we learned how to select specific one or more specific columns from a data frame using index or column names, with the help of an example programs.