seamless filtering of columns with dplyr without loosing rownames

If you use R and haven’t used dplyr yet, go and give it a try, it will be afternoon well spent. As much as I love this package, I probably haven’t used it yet as much as I should have – that’s because it requires you to shift your way of thinking about the problems a bit. To me, that’s similar as transitioning from basic R plotting functions to ggplot.

Today I worked with the dataframe where I needed to only keep rows where at least one of the columns has value greater than let’s say 15. So I did this:

filter_all(myDF, any_vars(. > 15))

However what happened was that I lost all my rownames where I keep important information. This is something that author of dplyr Hadley Wickham would refer to as “feature, not a bug”. This is because in complicated queries, rownames are hard to get right and it’s better to not to return anything than to get it wrong.

Therefore,  I will now need to keep my rownames as an additional column. And just today I came across very nice library that allows you do do that easily: tibble (note that it can do much more than this:). I like the readability of tibble commands a lot.

So here is my code:

myDF<-myDF %>% rownames_to_column('new_column') 
myDF<-filter_at(myDF, vars(-new_column), any_vars(. > 15))
myDF<-myDF %>% column_to_rownames('new_column')

This can be turn into one-liner, if that’s what you’re into.