Max
Max

Reputation: 725

using sapply on a vector of dates

I have a function that adds a random integer to a date:

rand_to_date = function(date){
newdate = as.Date(date) + sample(1:30, 1)
return(as.Date(newdate))
}

which works fine. However, if I attempt to use sapply to apply this function to a vector of dates, e.g.

test_dates = c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')

sapply will not return a vector of output in date format:

 sapply(test_dates,rand_to_date)
 2001-01-01 2002-02-02 2003-03-03 2004-04-04 
 11329      11748      12115      12513

In contrast, lapply will return a list of dates. However, applying unlist to this output once again gives me a vector of numbers rather than dates. Nor does

sapply(sapply(test,rand_to_date), as.Date)

work. What's the simplest way for me to give a vector of these randomized dates as output?

Upvotes: 1

Views: 229

Answers (4)

G. Grothendieck
G. Grothendieck

Reputation: 270268

1) Owing to the existence of the c.Date method, use lapply and then c. We have also simplified rand_to_date and added set.seed to make it reproducible:

rand_to_date <- function(date) as.Date(date) + sample(30, 1)

set.seed(123)
test_dates <- c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')

do.call("c", lapply(test_dates, rand_to_date))
## [1] "2001-01-10" "2002-02-26" "2003-03-16" "2004-05-01"

2) Alternately, we could make rand_to_date vectorized right off like this:

rand_to_date <- function(date) as.Date(date) + sample(30, length(date), TRUE)

set.seed(123)
test_dates <- c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')
rand_to_date(test_dates)
## [1] "2001-01-10" "2002-02-26" "2003-03-16" "2004-05-01"

Upvotes: 6

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

You can use as.character() within sapply :

sapply(test_dates,function(v) as.character(rand_to_date(v)),USE.NAMES = F)

where as.character(rand_to_date(v)) gives date as character, instead of POSIXct type.

Upvotes: 0

user10917479
user10917479

Reputation:

You can just convert the number back to a date.

as.Date(sapply(test_dates, rand_to_date), origin = "1970-01-01")

Upvotes: 0

Konrad Rudolph
Konrad Rudolph

Reputation: 546083

Unfortunately sapply discards attributes, including the S3 class — this is unrelated to your function; sapply(test_dates, as.Date) fails in the same way.

You need to add them again:

structure(sapply(test_dates,rand_to_date), 'Date')

Upvotes: 3

Related Questions