我一直在玩 R 的 gsub2 函数 R: replace characters using gsub, how to create a function? 来创建一个密文:
from<-c('s','l','k','u','m','i','x','j','o','p','n','q','b','v','w','z','f','y','t','g','h','a','e','d','c','r')
to<-c('z','e','b','r','a','s','c','d','f','g','h','i','j','k','l','m','n','o','p','q','t','u','v','w','x','y')
例如:
问题是,gsub2 将某些字母替换了两次(o->f->n 和 s->z->n),这弄乱了我的密文,几乎无法解码。有人能指出我犯的错误吗?谢谢!
最佳答案
一种方法是使用命名向量作为编码密码。创建此类命名向量的一种简单方法是使用 setNames
:
cipher <- setNames(to, from)
cipher
s l k u m i x j o p n q b v w z f y t g h a e d c r
"z" "e" "b" "r" "a" "s" "c" "d" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "t" "u" "v" "w" "x" "y"
对于编码功能,您可以使用
strsplit
和 paste
:encode <- function(x){
splitx <- strsplit(x, "")[[1]]
xx <- cipher[splitx]
xx[is.na(xx)] <- splitx[is.na(xx)]
paste(xx, collapse="")
}
encode("the who's 1973")
[1] "ptv ltf'z 1973"
关于用密文替换字母,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13503848/