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
We can subset with row_number
and which
library(dplyr)
df %>% filter(row_number() < which(A=='total'))
A B
1 Bob Smith 01005
2 Carl Jones 01008
3 Syndey Lewis 01185
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
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With