1

New to coding, so please bear with my simplistic question!

I have a dataframe:

date <- c(today()+1, today()+2, today()+3, today()+4, today()+5, today()+6)
precipitation <- c(0, 0, 35, 0, 0, 35)
weatherdataframe <- data.frame(date, precipitation)

I have another dataframe:

date2 <- c(today()-4, today()-7)
flag2 <- c("35mm24hrs", "10mm1hr")
emaillog <- data.frame(date2, flag2)

I'm trying to check for each date, whether it is expected to rain more than 35 mm. If it does, then check to see whether that date is within 3 days of today. If it is, then check the email log to ensure no emails have been sent out within 7 days of today, or if the emaillog is empty.

If all of these conditions are met, for example purposes, simply:

paste("flagged")

I've been trying it with if statements

if(((weatherdataframe$precipitation >= 35)&(weatherdataframe$date <= (today()+3)))&&
((emaillog$date2 <= (today() -7))||(length(unlist(emaillog$date2)) == 0))) {
paste("flagged")
}

but am getting the error

Warning message:
In if (weatherdataframe$precipitation>= 35) { :
  the condition has length > 1 and only the first element will be used

Coldest
  • 135
  • 1
  • 6

1 Answers1

1

As @akrun said in the comments, using ifelse makes more sense for this as it's vectorized (see https://stackoverflow.com/a/11865283/12957340 for further explanation) and you probably want to use any() or all() as well, e.g.

library(tidyverse)
library(lubridate)

date <- c(today()+1, today()+2, today()+3, today()+4, today()+5, today()+6)
precipitation <- c(0, 0, 35, 0, 0, 35)
weatherdataframe <- data.frame(date = date, precipitation = precipitation)
date2 <- c(today()-4, today()-7)
flag2 <- c("35mm24hrs", "10mm1hr")
emaillog <- data.frame(date2, flag2)

ifelse(
  any((weatherdataframe$precipitation >= 35) & (weatherdataframe$date <= (today() + 3)))
  && 
  any(all((emaillog$date2 <= (today() -7)), (length(unlist(emaillog$date2)) == 0))),
  paste("flagged"), 
  paste("nothing flagged")
  )
#> [1] "flagged"
Coldest
  • 135
  • 1
  • 6
jared_mamrot
  • 22,354
  • 4
  • 21
  • 46
  • Thanks for the help! This was mostly correct, just omitted an extra any() around the first emaillog criteria – Coldest Jul 14 '21 at 16:04