samedi 7 mars 2020

How to find the first row (date) of the series of 5 or more rows (date) with below 0 value in R

I have average temperature data with date below. I wanted to find the date which is the beginning of consistent below or above 0 Celsius in series of at least 5 days.

date_short mean.temp 1 2018-05-18 17.54 2 2018-05-19 19.45 3 2018-05-20 22.31 4 2018-05-21 13.26 5 2018-05-22 10.29 6 2018-05-23 15.06

I have used following scripts and found out how many days are below 0 and what rows meet the criteria of below 0 temperature. It shows that there are total of 147 days with below 0 degree temperature and in which row the below 0 temperature observed. From that I can see 161st date is the first day with below 0 temperature, but it is not what I wanted, because it is not the first date of the series of at least 5 days with below or above 0 degree. Instead I want R to return 170th day as it is the beginning of the series of at least 5 days with below or above 0 degree.

length(which(d.mean$mean.temp <= 0))
[1] 147
which(d.mean$mean.temp <= 0)
  [1] 161 162 166 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
 [30] 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
 [59] 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
 [88] 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
[117] 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 307 308 309 310 313 314 315 316 317
[146] 318 324

How can I do it in R. I can do it manually, but I have to find such date for many columns. In excel, the function would be something like below.

IF(B2<0, IF(B3<0, IF(B4<0, IF(B5<0, IF(B6<0,A2,""),""),""),""),"")

Thanks in advance

Aucun commentaire:

Enregistrer un commentaire