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.
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
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