This is my first time using elseif
. I wish to create a new column mobile$tenuredate
(in months) and am trying to find out the issue with my code that produced NA values.
Results
mobile$status == 'active'
rows give NA values for mobile$tenuredate
(they should not be NA).
mobile$status == 'stopped'
rows give valid values for mobile$tenuredate
.
Below is the code
mobile$tenuredate = if (mobile$status=="stopped") {
round(difftime(mobile$EFFECTIVEDATE, mobile$STARTDATE, units="weeks") / 4.348125)
} else if ((mobile$status == "active") && (mobile$difftemp >= 0)) {
round(difftime(mobile$CONTRACTENDDATE, mobile$STARTDATE, units="weeks") / 4.348125)
} else {
round(difftime(mobile$CUTOFFDATE, mobile$STARTDATE, units="weeks") / 4.348125)
}
Data file in CSV available here
Here's a sample dataframe.
structure(list(STARTDATE = structure(c(11413, 11639, 11953, 12212,
11335, 12050, 12142, 11225, 12176, 11386), class = "Date"), STOPDATE = structure(c(11436,
12079, NA, 12225, 11345, 12124, 12226, 11999, 12176, 11758), class = "Date"),
EFFECTIVEDATE = structure(c(11436, 12079, NA, 12225, 11345,
12124, 12226, 11999, 12176, 11758), class = "Date"), CONTRACTENDDATE = structure(c(11778,
12004, 12318, 12578, 11700, 12415, 12508, 11977, 12542, 11751
), class = "Date"), CUTOFFDATE = structure(c(12273, 12273,
12273, 12273, 12273, 12273, 12273, 12273, 12273, 12273), class = "Date"),
status = c("stopped", "stopped", "active", "stopped", "stopped",
"stopped", "stopped", "stopped", "stopped", "stopped"), tenuredate = structure(c(1,
14, NA, 0, 0, 2, 3, 25, 0, 12), class = "difftime", units = "weeks")), row.names = c(NA,
-10L), class = c("tbl_df", "tbl", "data.frame"))
Thanks in advance.