在R中加速运行if .. else循环

时间:2012-11-02 16:21:56

标签: r

有谁知道如何加快运行以下命令?我想用字符串替换数字“月”值...例如第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 个答案:

答案 0 :(得分: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]

答案 1 :(得分:4)

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

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

答案 2 :(得分: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])]}

答案 3 :(得分: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)