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

197 Views Asked by At

If I use df$columnName, you only get a vector which does not have the name of the column anymore. This means names(df$columnName) --> null

I could use df["columnName"], but this is kind of unhandy.. because I have to pass the columnName as string character.

2

There are 2 best solutions below

0
On BEST ANSWER

I prefer dplyr's select().

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

returns a one column dataframe.

0
On

Forming @Edo's great comment in an answer, we may use subset.

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

or short:

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

Data:

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