我正在使用 R 来累积来自传感器的每分钟数据。“宽度”和“高度”应该增加。不幸的是,数据包含 NA 和乱序值(例如,第 8 行的值 12.0、13.0 超出范围)。 我想要的是将无序值设置为 NA。
然后我将自己估算数据集'ex'。由于数据可能很大,我做了一个如下的程序:
m<-15
for(i in 2:m){
ex$WIDTH[i]<- ifelse(ex$WIDTH [i]- ex$WIDTH [i-1]<0,NA, ex$WIDTH [i])
ex$HEIGHT[i]<- ifelse(ex$HEIGHT[i]- ex$HEIGHT [i-1]<0,NA, ex$HEIGHT [i])
}
但结果是错误的。
原始数据集
ID CTIME WIDTH HEIGHT
1 HM001 201212121301 1201.9 1115.5
2 HM001 201212121302 1202.2 1115.8
3 HM001 201212121303 1202.8 1115.8
4 HM001 201212121304 NA 1116.1
5 HM001 201212121305 1203.9 1116.7
6 HM001 201212121306 NA 1116.7
7 HM001 201212121307 NA 1116.7
8 HM001 201212121308 12.0 31.0
9 HM001 201212121309 1206.0 1118.2
10 HM001 201212121310 1206.3 1118.6
11 HM001 201212121311 1206.5 1118.8
12 HM001 201212121312 NA NA
13 HM001 201212121313 1207.3 NA
14 HM001 201212121314 1207.9 1121.1
15 HM001 201212121315 1208.4 1121.3
for 语句的结果
ID CTIME ACTIVE_KWH REACTIVE_KWH
1 HM001 201212121301 1201.9 1115.5
2 HM001 201212121302 1202.2 1115.8
3 HM001 201212121303 1202.8 1115.8
4 HM001 201212121304 NA 1116.1
5 HM001 201212121305 NA 1116.7
6 HM001 201212121306 NA 1116.7
7 HM001 201212121307 NA 1116.7
8 HM001 201212121308 NA NA
9 HM001 201212121309 NA NA
10 HM001 201212121310 NA NA
11 HM001 201212121311 NA NA
12 HM001 201212121312 NA NA
13 HM001 201212121313 NA NA
14 HM001 201212121314 NA NA
15 HM001 201212121315 NA NA
我的期望(第 8 行宽度=NA,高度=NA)
ID CTIME WIDTH HEIGHT
1 HM001 201212121301 1201.9 1115.5
2 HM001 201212121302 1202.2 1115.8
3 HM001 201212121303 1202.8 1115.8
4 HM001 201212121304 NA 1116.1
5 HM001 201212121305 1203.9 1116.7
6 HM001 201212121306 NA 1116.7
7 HM001 201212121307 NA 1116.7
8 HM001 201212121308 NA NA
9 HM001 201212121309 1206.0 1118.2
10 HM001 201212121310 1206.3 1118.6
11 HM001 201212121311 1206.5 1118.8
12 HM001 201212121312 NA NA
13 HM001 201212121313 1207.3 NA
14 HM001 201212121314 1207.9 1121.1
15 HM001 201212121315 1208.4 1121.3