Bobby - 3 months ago 11

R Question

How can I subset a data frame:

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

such that I

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

To clarify from Zheyuan Li:

```
df[1]
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)
```