我正在尝试翻译具有月份编号的数据框上的一列(一月为 1,二月为 2,依此类推),因此我想将这些数字转换为西班牙语月份名称。首先我试过:
df$month <- month.name[df$month]
Run Code Online (Sandbox Code Playgroud)
这工作正常,但输出显示英文名称。
然后我尝试使用 gsub:
num <- c(1,2,3,4,5,6,7,8,9,10,11,12)
meses <- c("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio",
"Agosto","Septiembre","Octubre","Noviembre","Diciembre")
gsub2 <- function(pattern, replacement, x, ...) {
for(i in 1:length(pattern))
x <- gsub(pattern[i], replacement[i], x, ...)
x
}
df$month <- gsub2(num, meses,df$month)
Run Code Online (Sandbox Code Playgroud)
但是使用此代码,我的输出如下:
"Enero" "Febrero" "Marzo" "Abril" "Mayo"
"Junio" "Julio" "Agosto" "Septiembre" "Enero0" "EneroEnero" "EneroFebrero"
Run Code Online (Sandbox Code Playgroud)
我知道发生了什么,但我不知道如何解决它。提前致谢。
编辑:
df$month <- c(1, 2, 3, 4, 5, 6 ,7, 8, 9, 10, 11, 12)
Run Code Online (Sandbox Code Playgroud)
不使用正则表达式,可以通过矢量化更好地解决这个问题
unname(setNames(meses, num)[tabla$month])
#[1] "Abril" "Marzo" "Septiembre" "Julio" "Agosto" "Diciembre" "Abril" "Octubre" "Octubre" "Abril" "Agosto" "Mayo"
#[13] "Septiembre" "Septiembre" "Abril" "Noviembre" "Marzo" "Enero" "Julio" "Febrero"
Run Code Online (Sandbox Code Playgroud)
对应的tabla$month是
tabla$month
#[1] 4 3 9 7 8 12 4 10 10 4 8 5 9 9 4 11 3 1 7 2
Run Code Online (Sandbox Code Playgroud)
关于 的使用regex,可能我们需要添加 start( ^) 和 end( $) 以避免在or和for等1中多次获取匹配结果导致or111212"EneroEnero""EneroFebrero"
gsub2 <- function(pattern, replacement, x, ...) {
for(i in 1:length(pattern))
x<- gsub(paste0("^", pattern[i], "$"), replacement[i], x , ...)
x
}
gsub2(num, meses,tabla$month)
#[1] "Abril" "Marzo" "Septiembre" "Julio" "Agosto" "Diciembre" "Abril" "Octubre" "Octubre" "Abril" "Agosto" "Mayo"
#[13] "Septiembre" "Septiembre" "Abril" "Noviembre" "Marzo" "Enero" "Julio" "Febrero"
Run Code Online (Sandbox Code Playgroud)
set.seed(24)
tabla <- data.frame(month = sample(1:12, 20, replace = TRUE))
Run Code Online (Sandbox Code Playgroud)