0

I'm trying to replace some numbers (from 1 to 15) with a string value but it's not doing it correctly. Here's my code :

before = c("1","11","2","22")

after = c("A","B","c","E")

phrase = list( c("1","11") , c("2","22") )


for (i in phrase){
 
  r =  stringi::stri_replace_all_fixed(
    
    i , 
    
    before, 
    
    after, 
    
    vectorize_all = FALSE)
  
  print(r)
  
}

here's what I'm getting

[1] "A"  "AA"
[1] "c"  "cc"

how do I correct this?

r2evans
  • 141,215
  • 6
  • 77
  • 149
Akram H
  • 33
  • 4

2 Answers2

1

You don't need regular expressions since you are doing full text matching. You can create a look up vector and so a simple index replace

lookup <- setNames(after, before)

for (i in phrase){
  r <- unname(lookup[i])
  print(r)
}
# [1] "A" "B"
# [1] "c" "E"
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • the for loop can also be replaced by `map(phrase, ~n[.x])` if you like :-) – Mark Aug 23 '23 at 14:57
  • or `vapply(phrase, \(x) n[x], character(2L))` – Mark Aug 23 '23 at 15:00
  • 1
    mention might be made that `map(phrase, ` is `purrr::map(` for clarity. – Chris Aug 23 '23 at 15:12
  • 1
    Might be even easier to create `myLUT <- cbind(before, after)` and just write a loop around `myLUT[which(phrase[[j]][k] == myLUT[,1]),2]` (not tested) – Carl Witthoft Aug 23 '23 at 15:57
  • @CarlWitthoft if you post it as an answer I would upvote :-) – Mark Aug 24 '23 at 05:58
  • Your solution doesn't work when a string is composed of multiple numbers seperated by a seperator, something like c("1, 11, 2", "1", "22") for example @Mark – Akram H Aug 24 '23 at 07:42
  • It doesn't work in many contexts Akram, the question is, is it relevant to the actual data? – Mark Aug 24 '23 at 10:06
  • 1
    If the actual data is different from the example then change the example. You can't blame us if we assume the data is good – Mark Aug 24 '23 at 10:09
1

To cheer "Mark" up :-) , Might be even easier to create myLUT <- cbind(before, after) and just write a loop around myLUT[which(phrase[[j]][k] == myLUT[,1]),2] (not tested)

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
  • :-) :-) :-) :-) :-) :-) – Mark Aug 24 '23 at 14:22
  • 1
    I tested out `for (j in seq_along(phrase)){ for (k in seq_along(phrase[[j]])){ print(myLUT[which(phrase[[j]][k] == myLUT[,1]),2]) } }` and it works! – Mark Aug 24 '23 at 14:26