Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Rows occurring after a String R Data frame

I want to remove all rows after a certain string occurrence in a data frame column. I want to only return the 3 rows that appear above "total" appearing in column A. The 2 rows appearing below "total" would be excluded.

A            B       
Bob Smith    01005
Carl Jones   01008
Syndey Lewis 01185
total
Adam Price   01555
Megan Watson 02548
like image 905
bodega18 Avatar asked Sep 17 '25 02:09

bodega18


2 Answers

We can subset with row_numberand which

library(dplyr)

df %>% filter(row_number() < which(A=='total'))

             A     B
1    Bob Smith 01005
2   Carl Jones 01008
3 Syndey Lewis 01185
like image 84
GuedesBF Avatar answered Sep 18 '25 18:09

GuedesBF


You could use

library(dplyr)

df %>% 
  filter(cumsum(A == "total") == 0)

This returns

# A tibble: 3 x 2
  A            B    
  <chr>        <chr>
1 Bob Smith    01005
2 Carl Jones   01008
3 Syndey Lewis 01185

Data

structure(list(A = c("Bob Smith", "Carl Jones", "Syndey Lewis", 
"total", "Adam Price", "Megan Watson"), B = c("01005", "01008", 
"01185", NA, "01555", "02548")), problems = structure(list(row = 4L, 
    col = NA_character_, expected = "2 columns", actual = "1 columns", 
    file = "literal data"), row.names = c(NA, -1L), class = c("tbl_df", 
"tbl", "data.frame")), class = c("spec_tbl_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -6L), spec = structure(list(
    cols = list(A = structure(list(), class = c("collector_character", 
    "collector")), B = structure(list(), class = c("collector_character", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1L), class = "col_spec"))
like image 35
Martin Gal Avatar answered Sep 18 '25 18:09

Martin Gal