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


February 2019


908 time


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?):

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


вы можете использовать drop=FALSE, которые предотвращают от падают размеры массива.

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

Для subsetвас нужно добавить условие.