使用列名检索 data.frame 列的最佳方法是什么?

What is the best way to retrieve a column of a data.frame with its column name?

如果我使用 df$columnName,您只会得到一个不再具有列名称的向量。 这意味着 names(df$columnName) --> null

我可以使用 df["columnName"],但这有点不方便.. 因为我必须将 columnName 作为字符串字符传递。

我更喜欢dplyrselect()

library('dplyr')   
data = df %>% select(columnName)

returns 一列数据框。

形成@Edo的精彩回答,我们可以使用subset.

subset(x=dat, subset=, select=X1)

或简称:

subset(dat,,X1)
#   X1
# 1  1
# 2  2
# 3  3

数据:

dat <- structure(list(X1 = 1:3, X2 = 4:6, X3 = 7:9, X4 = 10:12), class = "data.frame", row.names = c(NA, 
-3L))