regex – Update Character Variables based on String Pattern in R

I currently have the below vector and am trying to use stringr to find a pattern and update.

string_vector <- c("1_lasso", "_lasso", "1_lasso_olsps", "_lasso_olsps")

string_vector_new <- string_vector %>%
str_replace("^[1_]_lasso", "Lasso")

[1] "Lasso"                 "_lasso"                "Lasso_olsps"          
 [4] "_lasso_olsps"

I’m not sure how, but I am hoping to update my code so that I can detect a pattern like 1_lasso and _lasso, and change them both to Lasso simultaneously. Is this possible using stringr? I’m not sure what regular expressions I would need to make that update and have many more variables like these ones.

Thanks in advance.

Product of the Month September 2016

Source link

Leave a Comment

Your email address will not be published. Required fields are marked *