【问题标题】:Change character string by key at R在 R 处按键更改字符串
【发布时间】:2021-10-03 08:23:41
【问题描述】:

这是一个数据框,例如:

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"))

如您所见,有一个名为“plant_sp”的列,其中包含 6 个字符的代码。 我想将此代码转换为新代码(如“NewName”列中的这种格式:

对于字母:

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

对于数字:

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

这样每个字符都会根据其值得到相反的值(0=9, 1=8...A=Z, B=Y...)

我该怎么做?管道解决方案会很棒。

非常感谢!

【问题讨论】:

标签: r dplyr tidyverse


【解决方案1】:

实现所需结果的一种方法是通过查找表和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

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多