5

有谁知道如何加快运行以下命令?我想用字符串替换数字“月”值……例如,第 1 个月转到“七月”。

这个命令真的很慢,因为我试图在其上实现它的数据框非常大!

for (i in 1:length(CO2$month)){
    if(CO2$month[i]=='1') {CO2$months[i]<-'Jul'} else
    if(CO2$month[i]=='2') {CO2$months[i]<-'Aug'} else
    if(CO2$month[i]=='3') {CO2$months[i]<-'Sept'} else
    if(CO2$month[i]=='4') {CO2$months[i]<-'Oct'} else
    if(CO2$month[i]=='5') {CO2$months[i]<-'Nov'} else
    if(CO2$month[i]=='6') {CO2$months[i]<-'Dec'} else
    if(CO2$month[i]=='7') {CO2$months[i]<-'Jan'} else
    if(CO2$month[i]=='8') {CO2$months[i]<-'Feb'} else
    if(CO2$month[i]=='9') {CO2$months[i]<-'Mar'} else
    if(CO2$month[i]=='10') {CO2$months[i]<-'Apr'} else
    if(CO2$month[i]=='11') {CO2$months[i]<-'May'} else
    if(CO2$month[i]=='12') {CO2$months[i]<-'Jun'}
}
4

4 回答 4

7

您可以在没有循环且没有 if-else 的情况下执行此操作:

set.seed(21)
CO2 <- data.frame(month=as.character(sample(1:12,24,TRUE)),
  stringsAsFactors=FALSE)
MonthAbbRotated <- month.abb[c(7:12,1:6)]
CO2$months <- MonthAbbRotated[as.numeric(CO2$month)]

如果你的month专栏不是真正的人物,这更容易:

set.seed(21)
CO2 <- data.frame(month=sample(1:12,24,TRUE))
MonthAbbRotated <- month.abb[c(7:12,1:6)]
CO2$months <- MonthAbbRotated[CO2$month]
于 2012-11-02T16:26:09.623 回答
4

我可能会遗漏一些东西,但为什么不只使用一个因素呢?

CO2$month <- factor(CO2$month, levels=1:12, labels=c("Jul","Aug","Sept","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun"))

于 2012-11-02T16:35:57.583 回答
1
month =c("jul","aug","sep","oct","nov","dec","jan","feb","mar","apr","may","jun")

for (i in 1:length(CO2$month)){ CO2$month[i] = month[as.integer(CO2$month[i])]}
于 2012-11-02T16:35:03.177 回答
1

这也可以工作,即使它是用于没有类似month.abb使用的简洁功能的东西:

Mon <- data.frame(month=1:12, months=c("Jul","Aug","Sept","Oct","Nov","Dec",
                                "Jan","Feb","Mar","Apr","May","Jun"))
CO2 <- merge(CO2, Mon, by="month", all.x=TRUE)
于 2012-11-02T16:36:42.223 回答