简体   繁体   English

替换许多不同的字符“一对一”吗? [R

[英]Replace many different characters “one by one”? R

Every now and then I encounter the following problem: I want to replace several characters in an object with "nicer" characters. 我时不时地遇到以下问题:我想用“ nicer”字符替换对象中的几个字符。 For instance, I want to change cryptic variable names to readable ones in tables for publication, or I want to change names of variables in a dataframe. 例如,我想将隐式变量名更改为表中可读的变量以进行发布,或者我想更改数据框中的变量名。 I typically end up implementing a copy & paste solution. 我通常最终会实现复制和粘贴解决方案。 For instance, 例如,

 dat <- mtcars
 names(dat) <- gsub("mpg", "Miles", names(dat))
 names(dat) <- gsub("cyl", "Cylinder", names(dat))
 ... etc

The pattern here is always the same: take an object with names (here it is the names of variables in a dataframe, but it could just be characters in any vector) and replace some elements with others, and repeat. 这里的模式始终是相同的:取一个带有名称的对象(这里是数据框中变量的名称,但是它可以是任何矢量中的字符),然后用其他元素替换某些元素,然后重复。

I am looking for way to do this more efficiently. 我正在寻找更有效地执行此操作的方法。 For instance, I have been thinking of sth along these lines: 例如,我一直在考虑以下方面:

 from <- c("mpg", "cyl")
 to   <- c("Miles", "Cylinder")
 names(dat) <- magic.function(from, to, names(dat))
 # ok, does not look like a big improvement, unless you think of 20 or 30 names...

I am looking for something that achieves the same as the following for -loop: 我在找的东西,达到相同以下for -loop:

 for(i in seq_along(from)){
      names(dat) <- gsub(from[i], to[i], names(dat))
 }

but in a more elegant (ie no loop) way. 但以更优雅(即无循环)的方式。 While it is easy to implement such a function myself, there probably is a built in function available doing this already, either in base or in some packages. 尽管我自己可以很容易地实现这样的功能,但是可能已经有一个内置函数可以执行此操作,无论是在基本版本还是在某些软件包中。 Does anyone know about such a function? 有人知道这样的功能吗?

I would suggest the "stringi" package for something like this: 我会建议使用“ stringi”软件包,例如:

library(stringi)
stri_replace_all_fixed(names(dat), from, to, vectorize_all = FALSE)
#  [1] "Miles"    "Cylinder" "disp"     "hp"       "drat"     "wt"      
#  [7] "qsec"     "vs"       "am"       "gear"     "carb"    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM