用定义的字符串列表替换非ascii字符,而不在R中使用循环

Álv*_*aro 6 replace r special-characters non-ascii-characters

我想用它们的ascii等效替换非ascii字符(现在只有西班牙语).如果我有"á",我想用"a"替换它,依此类推.

我构建了这个函数(工作正常),但我不想使用循环(包括像sapply这样的内部循环).

latin2ascii<-function(x) {
if(!is.character(x)) stop ("input must be a character object")
require(stringr)
mapL<-c("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","Ñ","ü","Ü")
mapA<-c("a","e","i","o","u","A","E","I","O","U","n","N","u","U")
for(y in 1:length(mapL)) {
  x<-str_replace_all(x,mapL[y],mapA[y])
  }
x
}
Run Code Online (Sandbox Code Playgroud)

有没有一种优雅的解决方法?任何帮助,建议或修改表示赞赏

Jos*_*ien 7

gsubfn() 在同名的包中对这类事情非常好:

library(gsubfn)

# Create a named list, in which:
#   - the names are the strings to be looked up
#   - the values are the replacement strings
mapL <- c("á","é","í","ó","ú","Á","É","Í","Ó","Ú","ñ","Ñ","ü","Ü")
mapA <- c("a","e","i","o","u","A","E","I","O","U","n","N","u","U")

# ll <- setNames(as.list(mapA), mapL) # An alternative to the 2 lines below
ll <- as.list(mapA)
names(ll) <- mapL


# Try it out
string <- "ÍÓáÚ"
gsubfn("[áéíóúÁÉÍÓÚñÑüÜ]", ll, string)
# [1] "IOaU"
Run Code Online (Sandbox Code Playgroud)

编辑:

G.格洛腾迪克指出,基地R也有这样的功能:

A <- paste(mapA, collapse="")
L <- paste(mapL, collapse="")
chartr(L, A, "ÍÓáÚ")
# [1] "IOaU"
Run Code Online (Sandbox Code Playgroud)