参数长度为零if语句

时间:2013-12-12 23:07:38

标签: r if-statement for-loop arguments zero

我有一个名为flow的数据框,包含超过17,000个条目,其中包含约50年的每日水质天数。我有一个列有每个条目的jday(一年中的一天),但现在我想为每个条目指定一个季节从1到4(冬天,春天,秋天,夏天)。这就是我到目前为止所做的:

> for(i in flow){
+   if (flow$jdays[i] <= 80 | flow$jdays[i]>355){
+   flow$season [i] <- 1
+   } else if (flow$jdays [i] > 80 & flow$jdays [i]<= 172){
     flow$season [i] <- 2
+   }
+   else if(flow$jdays [i] > 172 & flow$jdays [i]<= 264){
+     flow$season [i] <- 3
+   }
+   else{
+     flow$season [i] <- 4
+   }
+ }

我不断收到以下消息:

Error in if (flow$jdays[i] <= 80 | flow$jdays[i] > 355) { : 
argument is of length zero

3 个答案:

答案 0 :(得分:1)

这可能是更好的方法,

flow$season<-ifelse(flow$jdays<=80 | flow$jdays>355 ,1,
                   ifelse(flow$jdays<=172,2,
                         ifelse(flow$jdays<=264,3,4)))

答案 1 :(得分:0)

这是错误的:

for(i in flow){

更改为:

for(in in seq(nrow(flow))){

答案 2 :(得分:0)

使用ifelse的矢量化解决方案:

transform(flow, season=
            ifelse (jdays <= 80 | jdays>355, 1,
                ifelse(jdays <= 172,2,
                    ifelse(jdays <= 264,    3,  4))))