I have imported a CSV file with numerous dates and have use the as.Date function to convert the date. However, when I use the the mapply function to find the earlier of two dates, I either end up with a list with dates or a numeric vector. How can I get a vector with dates?
POP.Start.final <- mapply(min, combinedOM$Cons.Start.Date.y,
combinedOM$OS.Start.Date.y,
MoreArgs = list(na.rm=T),SIMPLIFY=T)
This returns a numeric vector, changing to SIMPLIFY=F returns a list of dates, but I want a vector of dates.
Difference between lapply() and sapply() functions:lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects.
sapply is a user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify = "array" , an array if appropriate, by applying simplify2array() . sapply(x, f, simplify = FALSE, USE. NAMES = FALSE) is the same as lapply(x, f) .
The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object. Since the lapply() function applies a certain operation to all the elements of the list it doesn't need a MARGIN. Syntax: lapply( x, fun )
lapply,List-method in the S4Vectors package for an example of a specific lapply method (defined for List objects).
In this specific case, I believe pmin
does the trick:
POP.Start.final <- pmin(combinedOM$Cons.Start.Date.y,
combinedOM$OS.Start.Date.y,
na.rm=TRUE)
In the general case, SIMPLIFY=TRUE
(the default) uses the utility function simplify2array
to convert lists to vectors of atomic mode via as.vector
. Because dates are internally stored as numeric, SIMPLIFY=TRUE
will convert the list of dates to a vector of mode numeric and remove the Date
class. You can set SIMPLIFY=FALSE
to keep the Date
class and then use do.call
with c
to convert the list to a vector.
POP.Start.final <- do.call(c,mapply(min, combinedOM$Cons.Start.Date.y,
combinedOM$OS.Start.Date.y,
MoreArgs = list(na.rm=TRUE),SIMPLIFY=FALSE))
Some reproducible code:
a <- as.Date(c("2012-01-11","2012-06-30","2012-04-18"))
b <- as.Date(c("2013-04-21","2012-03-22","2012-05-01"))
pmin(a,b)
#[1] "2012-01-11" "2012-03-22" "2012-04-18"
do.call(c,mapply(min,a,b,MoreArgs=list(na.rm=TRUE),SIMPLIFY=FALSE))
#[1] "2012-01-11" "2012-03-22" "2012-04-18"
As an aside, using T
and F
for TRUE
and FALSE
is slightly worrying because T
and F
can be reassigned while TRUE
and FALSE
cannot be reassigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With