filter R data frame with one column - keep data frame format [duplicate]

Refresh

February 2019

Views

945 time

1

This question already has an answer here:

I am looking for a simple way to display a subset of a one column data frame Let's assume, I have a a data frame:

> df <- data.frame(a = 1:100)

Now, I only need the first 10 rows. If I subset it by index, I'll get a result vector instead of a data frame:

> df[1:10,]
 [1]  1  2  3  4  5  6  7  8  9 10

I tried to use 'subset' but not using the 'subset'-parameter will result in an error (only for one-column-data-frames?):

subset(df[1:10,])
Error in subset.default(df[1:10, ]) : 
  argument "subset" is missing, with no default

There should be a very easy solution to achive a subset (still a data frame) filtered by row index, no? I am lookung for a solution with basic R commands (it should not depend on any special library)

1 answers

4

you can use drop=FALSE, which prevent from droping the dimensions of the array.

df[1:10, , drop=FALSE]
    a
1   1
2   2
3   3
4   4
5   5
...

For subset you need to add a condition.