How to delete a set of specific rows, listed in a vector, from a data frame in R?

3
Hello, I have a data.frame with thousands of rows and a vector with the rows I need this date.frame, how do I select only rows from the list in a separate object?

    
asked by anonymous 05.11.2014 / 04:02

2 answers

2

Suppose you have a date.frame like this:

 df <- data.frame(a = 1:10, b = 1:10)

And you want to select only the lines 1,5 and 8 that are in the vector:

linhas <- c(1,5,8)

Then you can select and save them to a new object as follows:

df.novo <- df[linhas,]
df.novo
  a b
1 1 1
5 5 5
8 8 8

If you wanted to delete lines 1,5 and 8 you could do it as follows:

df.novo <- df[-linhas, ]
df.novo
    a  b
2   2  2
3   3  3
4   4  4
6   6  6
7   7  7
9   9  9
10 10 10
    
05.11.2014 / 13:07
1

Use dplyr ():

Import packages

library(dplyr)

Sample Data Frame

df <- data.frame(a = 1:5, b = 1:5)

Removing line 1 and 2, for example:

df <- df %>% slice(3:n())
    
13.09.2018 / 15:32