1

here is a dataframe for example:

test_df <- structure(list(plant_id = c("AB1234", "CC0000", "ZX9998", "AA1110", "LO8880"), 
                          NewName = c("ZY8765", "XX9999", "AC0001", "ZZ8889", "OL1119")), 
                     row.names = c(NA, -5L), class = "data.frame", 
                     .Names = c("plant_sp", "NewName"))

As you can see, there is a column call "plant_sp" with a 6 character code. I'd like to tansform this code to a new code (like at column "NewName" by this format:

For letters:

A-Z
B-Y
C-X
D-W
E-V
F-U
G-T
.
.
.

For numbers:

0-9
1-8
2-7
3-6
4-5
5-4
.
.
.
 plant_sp NewName
1   AB1234  ZY8765
2   CC0000  XX9999
3   ZX9998  AC0001
4   AA1110  ZZ8889
5   LO8880  OL1119

So that each character will get the opposite one by its value (0=9, 1=8... A=Z, B=Y...)

How can I do it? a pipe solution would be great.

Thanks a lot!

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Ido
  • 201
  • 1
  • 8
  • Related: [Replace / translate characters in a string](https://stackoverflow.com/questions/6954017/replace-translate-characters-in-a-string); `chartr`. – Henrik Oct 03 '21 at 10:14

1 Answers1

1

One option to achieve your desired result would be via a lookup table and stringr::str_replace_all:

library(dplyr)
library(stringr)

lt_letters <- setNames(rev(LETTERS), LETTERS)
lt_numbers <- setNames(rev(0:9),0:9)

test_df %>% 
  mutate(NewName1 = str_replace_all(plant_sp, "[A-Z0-9]", function(x) c(lt_letters, lt_numbers)[x]))
#>   plant_sp NewName NewName1
#> 1   AB1234  ZY8765   ZY8765
#> 2   CC0000  XX9999   XX9999
#> 3   ZX9998  AC0001   AC0001
#> 4   AA1110  ZZ8889   ZZ8889
#> 5   LO8880  OL1119   OL1119
stefan
  • 90,330
  • 6
  • 25
  • 51