我有这段代码来删除字符串中的前导零,我想知道是否可以提高其速度
rmleadingzeros <- function(x){
x <- as.numeric(sapply(x,gsub,pattern="00",replacement="0"))
x <- as.numeric(sapply(x,gsub,pattern="01",replacement="1"))
x <- as.numeric(sapply(x,gsub,pattern="02",replacement="2"))
x <- as.numeric(sapply(x,gsub,pattern="03",replacement="3"))
x <- as.numeric(sapply(x,gsub,pattern="04",replacement="4"))
x <- as.numeric(sapply(x,gsub,pattern="05",replacement="5"))
x <- as.numeric(sapply(x,gsub,pattern="06",replacement="6"))
x <- as.numeric(sapply(x,gsub,pattern="07",replacement="7"))
x <- as.numeric(sapply(x,gsub,pattern="08",replacement="8"))
x <- as.numeric(sapply(x,gsub,pattern="09",replacement="9"))
return(x)
}
datainOKdate$mo <- rmleadingzeros(datainOKdate$mo)
非常感谢
答案 0 :(得分:3)
x <- paste0(0, 1:9)
x
# [1] "01" "02" "03" "04" "05" "06" "07" "08" "09"
as.numeric(x)
# [1] 1 2 3 4 5 6 7 8 9
更新以下评论
如果x
是一个因素,我们必须更加小心。请参阅?factor
x <- as.factor(paste0(0, c(1, 11, 22, 3)))
x
# [1] 01 011 022 03
# Levels: 01 011 022 03
as.numeric(x)
# [1] 1 2 3 4
# not what we want
# This is the way according to ?factor
as.numeric(as.character(x))
# [1] 1 11 22 3
as.numeric(levels(x))[x]
# [1] 1 11 22 3