Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering single-column data frames

Tags:

dataframe

r

I am attempting to filter data frames that have only one column. This results in a vector being returned like so:

single.c <- data.frame(col1=c(1,2,3,4,5), row.names=C("r1","r2","r3","r4","r5"))
single.c[single.c$col1 > 2,]

[1] 3 4 5

What I actually want is the data returned like it is for multi-column dataframes:

multi.c <- data.frame(col1=c(1,2,3,4,5), col2=c(1,2,3,4,5), row.names=c("r1","r2","r3","r4","r5"))
multi.c[multi.c$col2 > 2,]

   col1 col2
r3    3    3
r4    4    4
r5    5    5

I can see it makes sense to return a vector if there are no other columns, but generally I want see what rows have given that result too. Why does this happen, and is there an easy way to keep the data frame shape in the result, including the rownames?

like image 408
MattLBeck Avatar asked Aug 23 '12 11:08

MattLBeck


1 Answers

Use the drop argument to the select functions:

single.c[single.c$col1 > 2, ,drop=F]

#   col1
#r3    3
#r4    4
#r5    5

From documentation for [:

drop

For matrices and arrays. If TRUE the result is coerced to the lowest possible dimension (see the examples). This only works for extracting elements, not for the replacement. See drop for further details.

like image 86
Andy Avatar answered Oct 20 '22 01:10

Andy