如何通过列名提取data.frame列并保留列名?求最优方法
Great question! I totally get the annoyance of either losing column names when using df$columnName (since that returns a plain vector where names(df$columnName) is NULL) or having to type string quotes every time with df["columnName"]. Here are the best, most efficient ways to extract columns while keeping their names intact:
1. Base R: Use [, drop = FALSE]
This is the simplest base R solution. By default, when you extract a single column with df[, "columnName"], R converts it to a vector (thanks to the drop = TRUE default). Setting drop = FALSE forces R to return a 1-column data.frame, which retains the original column name.
Example:
# Create sample data df <- data.frame( name = c("Alice", "Bob", "Charlie"), age = c(25, 30, 35) ) # Extract "age" column with name preserved age_col <- df[, "age", drop = FALSE] # Check the result names(age_col) # Returns "age" class(age_col) # Returns "data.frame" (not a vector)
This method also works seamlessly with dynamic column names stored in variables:
target_col <- "age" age_col <- df[, target_col, drop = FALSE]
2. Tidyverse: Use dplyr::select()
If you’re working with the tidyverse ecosystem, select() from the dplyr package is incredibly clean and readable. You can pass unquoted column names directly, and it returns a data.frame with all original column names intact.
Example:
library(dplyr) # Extract "age" column age_col <- select(df, age) # Verify names(age_col) # Returns "age"
For dynamic column names, use all_of() to reference the variable safely:
target_col <- "age" age_col <- select(df, all_of(target_col))
Bonus: select() makes extracting multiple columns at once trivial while preserving all their names (e.g., select(df, name, age)).
Which Should You Use?
- Stick with the base R
[, drop = FALSE]method if you want to avoid external dependencies. - Go with
dplyr::select()if you’re already using tidyverse tools—it’s more intuitive, especially for complex column selections.
Content of the question comes from Stack Exchange, asked by Marcel Gangwisch

