Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace_all by position, applied over a vector

I have a data frame where each entry is some number of strings, separated by commas. I want a neat way to replace every element by position.

here's a toy version of the data

 library(tidyverse)

d1 <- tibble(
  r1 = c("lab1",
         "lab2,lab3",
         NA,
         "lab3,lab4"),
  r2 = c(NA,
         "lab1",
         "lab2",
         "lab2,lab3")
  ) 

So every lab element I want replacted by the corresponding rep element.

d1 %>% 
  modify_at(1:2,
        ~ str_replace_all(.,
                          c("lab1", "lab2", "lab3", "lab4"),
                          c("rep1", "rep2", "rep3", "rep4")))

Returns

# A tibble: 4 x 2
         r1        r2
      <chr>     <chr>
1      rep1      <NA>
2 rep2,lab3      lab1
3      <NA>      lab2
4 lab3,rep4 lab2,lab3

so I've only made a single replacement per cell in r1, whereas I need to replace them all.

like image 498
tomw Avatar asked Dec 24 '22 14:12

tomw


1 Answers

This should work

  d1 %>% 
      modify_at(1:2,
                ~ stringr::str_replace_all(.,
                                           c("lab1" = "rep1",
                                             "lab2" = "rep2",
                                             "lab3" = "rep3",
                                             "lab4" = "rep4")))

To perform multiple replacements in each element of string, pass a named vector (c(pattern1 = replacement1)) to str_replace_all

like image 129
missuse Avatar answered Jan 08 '23 01:01

missuse