Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove rows from data frame using row indices where row indices might be zero length vector

Tags:

dataframe

r

dplyr

I want to drop some rows from some dataframe using numeric indices of the rows. But sometimes the indices vector that I am going to drop becomes zero length vector. In this case, I expect that nothing should be dropped from the original data frame. But instead of nothing everything is dropped.

For example, here drop works as expected

df = data_frame( a = 10:12 )
drop = c(1,2)
df[ -drop, ]
# # A tibble: 1 × 1
# a
# <int>
# 1    12

But when drop is zero length vector, then removing those rows doesn't work as I expect.

drop = integer()
df[ -drop, ]
# A tibble: 0 × 1
# ... with 1 variables: a <int>

I was expecting to get the whole df object without any modification.

How to remove rows from a data frame using row indices safely where row indices might become a zero length vector?

like image 617
Mert Nuhoglu Avatar asked May 30 '17 15:05

Mert Nuhoglu


1 Answers

For this reason, it is better to use %in% and negate ! it

df[!seq_len(nrow(df)) %in% drop, ]

As it is a data_frame, we can use tidyverse methods

df %>%
   filter(!row_number() %in% drop)
like image 178
akrun Avatar answered Oct 12 '22 08:10

akrun