Aren Cambre Aren Cambre - 27 days ago 21
R Question

Extracting specific columns from a data frame

I have an R data frame with 6 columns, and I want to create a new dataframe that only has three of the columns.

Assuming my data frame is

df
, and I want to extract columns
A
,
B
, and
E
, this is the only command I can figure out:

data.frame(df$A,df$B,df$E)


Is there a more compact way of doing this?

Answer

Yes, there is.

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[,c("A","B","E")]