Delete rows from data frame using row indices, where row indices can be a zero-length vector

I want to remove some rows from some data frame using row index numbers. But sometimes the index vector that I'm going to fall becomes a zero-length vector. In this case, I expect that nothing should be removed from the original data frame. But instead of nothing, everything is discarded.

For example, it dropworks as expected here

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

But when drop- a vector of zero length, then deleting these lines does not work, as I expect.

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

I expected to get the whole object dfwithout any changes.

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

+4
2

%in% ! it

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

data_frame, tidyverse

df %>%
   filter(!row_number() %in% drop)
+4

, !

df   <- data.frame(a = 10:12)
drop <-  c(1,2)
'if'(length(drop) == 0, df, df[-drop, ])

drop <-  integer()
'if'(length(drop) == 0, df, df[-drop, ])
0

Source: https://habr.com/ru/post/1678180/


All Articles