0

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

2
  • you can use subset(dataset, !condition), or dplyr::filter(dataset, !condition). For example, subset(debris_removed_stats, id != "i") Commented Aug 30, 2022 at 18:57
  • Perhaps you want to update the row names after removing rownames(debris_removed_stats) <- NULL. Commented Aug 30, 2022 at 19:58

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.