Skip to content
Prev 345536 / 398502 Next

range () does not remove NA's with complete.cases() for dates (dplyr/mutate)

Pradip,

For some reason mutate is not setting the is.NA value for the new column. Note the output below using your data structures.
[1] NA
[1] NA
[1] "numeric"
[1] "numeric"
Date[1:1], format: NA
Date[1:1], format: NA
[1] "Date"
[1] "Date"
[1] FALSE
[1] "'is.NA' value mismatch: 0 in current 1 in target"
## functioning code
data2$mrjdate[2]
data2$oiddate[2]
mrj <- data2$mrjdate[2]
oid <- data2$oiddate[2]
mode(mrj)
mode(oid)
str(mrj)
str(oid)
class(mrj)
class(oid)
# But note:
identical(mrj, oid)
all.equal(mrj, oid)

## This ugly solution does not have the problem.
+   if (all(is.na(unlist(data1[row, -1])))) {
+     max_d <- NA
+   } else {
+     max_d <- max(unlist(data1[row, -1]), na.rm = TRUE)
+   }
+   max_d}),
+   origin = "1970-01-01")
[1] "2004-11-04" "2009-10-24"
[1] "2005-08-10" "2011-10-05"
[1] "2005-07-07" "2011-10-13"
[1] "2007-11-07" "2011-11-04"
[1] "2006-09-01" "2011-11-04"
Working code below.

data3 <- data1
data3$oiddate <- as.Date(sapply(seq_along(data3$id), function(row) {
  if (all(is.na(unlist(data1[row, -1])))) {
    max_d <- NA
  } else {
    max_d <- max(unlist(data1[row, -1]), na.rm = TRUE)
  }
  max_d}),
  origin = "1970-01-01")

range(data3$mrjdate[complete.cases(data3$mrjdate)])
range(data3$cocdate[complete.cases(data3$cocdate)])
range(data3$inhdate[complete.cases(data3$inhdate)])
range(data3$haldate[complete.cases(data3$haldate)])
range(data3$oiddate[complete.cases(data3$oiddate)])
On Nov 10, 2014, at 10:10 AM, Muhuri, Pradip (SAMHSA/CBHSQ) wrote:

            
NOTICE:  This E-Mail (including attachments) is confidential and may be legally privileged.  It is covered by the Electronic Communications Privacy Act, 18 U.S.C.2510-2521.  If you are not the intended recipient, you are hereby notified that any retention, dissemination, distribution or copying of this communication is strictly prohibited.  Please reply to the sender that you have received this message in error, then delete it.