How to replace string for every row in specfic column using dplyr and stringr

Viewed 12114

I have the following tibble:


library(tidyverse)

df <- tibble::tribble(
  ~sample, ~colB, ~colC,
  "foo",   1,  2,
  "bar_x",   2,  3,
  "qux.6hr.ID",   3,  4,
  "dog",   1,  1
)


df
#> # A tibble: 4 x 3
#>       sample  colB  colC
#>        <chr> <dbl> <dbl>
#> 1        foo     1     2
#> 2      bar_x     2     3
#> 3 qux.6hr.ID     3     4
#> 4        dog     1     1

df <- factor(final_df$samples, levels=c("bar_x","foo","qux.6hr.ID","dog"))

    df
#> [1] foo        bar_x      qux.6hr.ID dog       
#> Levels: bar_x foo qux.6hr.ID dog

What I want to do is for every row in sample column remove these substrings: _x and .6hr if exist. The final table looks like this:

     sample  colB  colC
        foo     1     2
        bar     2     3
     qux.ID     3     4
        dog     1     1

How can I achieve that?

2 Answers

And here's a solution using the purrr:map function, which has the added benefit of returning the same result whether "sample" is chr or factor.

df %>%
   mutate(sample = map_chr(sample, ~str_replace(.x, 
                                         pattern = "_x|\\.\\d+[A-Za-z]+", 
                                         replacement = "")))
# A tibble: 4 x 3
#  sample  colB  colC
#  <chr>  <dbl> <dbl>
#1 foo        1     2
#2 bar        2     3
#3 qux.ID     3     4
#4 dog        1     1
Related