Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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)

like image 544
Antje Janosch Avatar asked Mar 15 '23 23:03

Antje Janosch


1 Answers

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.

like image 74
Mamoun Benghezal Avatar answered Mar 18 '23 16:03

Mamoun Benghezal