Home > Blockchain >  Replacing a string found in a list with a string
Replacing a string found in a list with a string

Time:06-15

Using tidyverse, across the entire data frame, replacing any string found on a list, with a string.

df<- tribble(
  ~x, ~y,  ~z,
  "a", "95%",  "96%",
  "b", "99%",  "98%",
  "c", "astricks", "astricks"
)

high95 <- c("95%", "96%", "97%", "98%", "99%", "100%")

Trying to replace any string in the list (high95) with the string ">95%"

df %>% str_replace(. %in% high95, ">95%")

I am doing this with strings because of suppression changing col to a character format.

CodePudding user response:

We may use replace to create the logical expression

library(dplyr)
df <- df %>% 
   mutate(across(y:z, ~ replace(., . %in% high95, ">95%")))

-output

df
# A tibble: 3 × 3
  x     y        z       
  <chr> <chr>    <chr>   
1 a     >95%     >95%    
2 b     >95%     >95%    

CodePudding user response:

You can use high95 to create a regex that matches these values and use this regex in str_replace:

library(dplyr)
library(stringr)

df<- tribble(
  ~x, ~y,  ~z,
  "a", "95%",  "96%",
  "b", "99%",  "98%",
  "c", "astricks", "astricks"
)

high95 <- c("95%", "96%", "97%", "98%", "99%", "100%")
regex_95 <- paste0("(", paste0(high95, collapse = "|"), ")")
regex_95
#> [1] "(95%|96%|97%|98%|99%|100%)"

df %>% 
  mutate(across(everything(), ~str_replace(.x, regex_95, ">95%")))
#> # A tibble: 3 × 3
#>   x     y        z       
#>   <chr> <chr>    <chr>   
#> 1 a     >95%     >95%    
#> 2 b     >95%     >95%    
#> 3 c     astricks astricks

Created on 2022-06-14 by the reprex package (v1.0.0)

CodePudding user response:

Different option using replace:

data.frame(lapply(df, function(x) {replace(x, x %in% high95, ">95%")}))

Output:

  x        y        z
1 a     >95%     >95%
2 b     >95%     >95%
3 c astricks astricks
  • Related