title: ifelse statement within a data.table query in R
body: <p>I have an issue with conditional statement in data.table.</p>
  
  <p>My DF is made of different dates associated with different ids. And I want to get the max date for each id. But:</p>
  
  <p><strong>EDIT</strong>: Here is the DF, sorry:</p>
  
  <pre><code>df &lt;- data.frame(id=c(1,1,1,1,2,3,3,3,4,5,5,5,5),
                   date=c("2016-01-21", "2016-01-13", NA, "2016-01-13",
                          "2016-01-13", "2016-01-13", "2016-02-02", "2016-01-25", NA,
                          "2016-01-25", "2016-01-25", "2016-01-25", "2016-01-25"))
  </code></pre>
  
  <p>If I don't include the ifelse fonction, data.table gives me a warning because of the single NA for ID 4 which as been removed during the process</p>
  
  <pre><code>agg &lt;- setDT(df)[,
                   .SD[,
                       .(max_date=max(as.Date(date), na.rm=TRUE))
                       ],
                   by=.(id)
                   ]
  </code></pre>
  
  <blockquote>
    <p>Warning message: In max.default(NA_real_, na.rm = TRUE) :   no
    non-missing arguments to max; returning -Inf</p>
  </blockquote>
  
  <p>This warning appears explicitly in the documentation of <code>?max</code> </p>
  
  <blockquote>
    <p>For min and max if there are only numeric inputs and all are empty
    (after possible removal of NAs), the result is double (Inf or -Inf).</p>
  </blockquote>
  
  <p>If I handle this problem with a condition, I get an error:</p>
  
  <pre><code>agg &lt;- setDT(df)[,
                   .SD[,
                       .(max_date=ifelse(
                          (is.na(as.Date(date)) &amp; .N == 1),
                          max(as.Date(date), na.rm=TRUE),
                          NA))
                       ],
                   by=.(id)
                   ]
  </code></pre>
  
  <blockquote>
    <p>Error in <code>[.data.table</code>(setDT(df), , .SD[, .(max_date =
    ifelse((is.na(as.Date(date)) &amp;  :    Column 1 of result for group 4 is
    type 'double' but expecting type 'logical'. Column types must be
    consistent for each group. In addition: Warning message: In
    max.default(NA_real_, na.rm = TRUE) :   no non-missing arguments to
    max; returning -Inf</p>
  </blockquote>
  
  <p>So my question is double:</p>
  
  <ul>
  <li>I don't understand the later error from data.table</li>
  <li>How can I include an ifelse statement in data.table when it comes to assigning a value to a new variable (given that I want to store the result in another DT, no modification by reference.)</li>
  </ul>
  
  <p>Thanks</p>