R - De/Select Columns
Use the following syntax to Select (or Deselect) specific columns in a data frame in base R:
- Select columns by Name
df_trim <- df[c('col1', 'col2', 'col4')]
- Select columns by Index
df_trim <- df[c(1, 2, 4)]
- To De-Select columns by Index
df_trim <- df[-c(1, 2, 4)]
- I have used the code below to help me discern the column names and their numbers.
col_labels <- colnames(df)
for (i in seq(1, length(col_labels))) {
print(paste(i, col_labels[i], sep=": "))
}
1: colname1
2: colname2
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.