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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With