Bobby Bobby - 10 months ago 49
R Question

Subset a data frame and always receive a data frame as the return type

How can I subset a data frame:

df <- data.frame(a = c(1,2,3), b = c(4,5,6))

such that I always get a data frame back even if only one column is selected?

Result as desired when selecting two columns:

class( df[,1:2] )
[1] "data.frame"

Result not as desired when selecting only one column:

class( df[,1] )
[1] "numeric"

Desired result when selecting one column would be equivalent to:

class( data.frame(a = c(1,2,3) )

Answer Source

To clarify from Zheyuan Li:

df[,1, drop = FALSE]

return a data frame with only column 1.

If you want to subset rows as well as columns, these work for me:

df[1:2, 1, drop = FALSE]
subset(df[1], a < 3)   
subset(df, subset = a<3, select = a)