Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove rows with specific row numbers using dplyr's pipe function

Tags:

r

I am looking for some way to delete specific rows by row numbers using dplyr's pipe function

library(dplyr)
head(mtcars)

Now let say I want remove row numbers c(1, 4, 7). Typically we would use mtcars[-c(1, 4, 7), ] to do the same.

However I want to use pipe to do the same.

Is there any way to do this?

Any pointer will be highly appreciated.

like image 841
Brian Smith Avatar asked Sep 04 '26 20:09

Brian Smith


2 Answers

We can use slice

library(dplyr)
mtcars %>%
   slice(-c(1, 4, 7))

Or if we want to use [

mtcars %>%
      `[`(-c(1, 4, 7),)

Or use extract from magrittr

library(magrittr)
mtcars %>%
    extract(-c(1, 4, 7),)
like image 168
akrun Avatar answered Sep 06 '26 10:09

akrun


We could use filter

library(dplyr)

# vector for rows to remove
to_remove <- c(1, 4, 7)

mtcars %>%
  filter(!row_number() %in% to_remove)
like image 37
TarJae Avatar answered Sep 06 '26 11:09

TarJae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!