Hayley Schmidman
Hayley Schmidman

Reputation: 11

How do I remove a row in a data frame without using a row number?

I would like to delete a row in my data frame by not using the row number but instead an identifier within the row itself. This is because in the future the dataframe will be updated with new data, and the row number will not be in the same place. So having code that deletes one row I don't want now, specified by only the row number will cause a row that I want to keep to be deleted in the future. Any help with this is greatly appreciated as I am quite stuck!

This is the code I was using that used row number instead of a row identifier:

debris_removed_stats <- slice(debris_removed_stats, -c(22))

I attempted many other functions that used a similar -c(...) form, but each time I put in the identifier of the unwanted row i I got back the error message Error in ~-c(i) : object 'i' not found

debris_removed_stats <- slice(debris_removed_stats, -c(i))

debris_removed_stats <- debris_removed_stats[!(debris_removed_tidy$id %in% c(i)), ].

Here is a part of the data frame for some context as well: debris_removed_stats Data Frame

Upvotes: 0

Views: 785

Answers (1)

Bushidov
Bushidov

Reputation: 723

Here are some examples on how to achieve this:

Data

df= data.frame(id = c('1', '2', 'i', '3'), b = c(10:13))

  id  b
1  1 10
2  2 11
3  i 12
4  3 13

Dplyr options:

  • Using your slice approaches:

    slice(df, -which(df$id=="i"))
    
  • Using filter (as mentionned by @Andrea in comments)

    df %>% filter(id != 'i')
    

Base options:

df[-which(df$id=="i"),]

or

subset(df, id != 'i')

All options resulting in:

  id  b
1  1 10
2  2 11
3  3 13

Upvotes: 1

Related Questions