Reputation: 1430
I need to remove elements from a vector after a string match as below:
months = c("jan", "feb", "mar", "apr", "may", "jun",
"jul", "ago", "sep", "oct", "nov", "dec")
month = "jun"
### ENTER MAGIC ###
# desired output
months
#> [1] "jan" "feb" "mar" "apr" "may" "jun"
Created on 2020-07-21 by the reprex package (v0.3.0)
Any ideas?
Upvotes: 1
Views: 97
Reputation: 887891
An option with cumsum
months[cumsum(cumsum(months == month)) <2]
#[1] "jan" "feb" "mar" "apr" "may" "jun"
Or with match
months[seq_len(match(month, months))]
Upvotes: 0
Reputation: 1089
Like this?
months[1:which(months == month)]
or if you do not want to include the last entry
months[1:which(months == month)-1]
Upvotes: 0
Reputation: 4233
Assuming there is a single match, you can do the following:
months <- months[1:which(months == month)]
Output
> months
[1] "jan" "feb" "mar" "apr" "may" "jun"
Upvotes: 2