You can subset using a vector of column names. I strongly prefer this approach over those that treat column names as if they are object names (e.g. subset()
), especially when programming in functions, packages, or applications.
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
df[c("A","B","E")]
Note there's no comma (i.e. it's not df[,c("A","B","C")]
). That's because df[,"A"]
returns a vector, not a data frame. But df["A"]
will always return a data frame.
str(df["A"])
str(df[,"A"])
Thanks to David Dorchies for pointing out that df[,"A"]
returns a vector instead of a data.frame, and to Antoine Fabri for suggesting a better alternative (above) to my original solution (below).
df[,c("A","B","E")]
df[,"A"]