Emma
Emma

Reputation: 37

Apply function to get months from today's date

I'm trying to create a column in a dataset that tells me the (approximate) number of months a customer has been with the company.

This is my current attempt:

dat <- data.frame(ID = c(1:4), start.date = as.Date(c('2015-04-09', '2014-03-  24', '2016-07-01', '2011-02-02')))
dat$months.customer <- apply(dat[2], 1, function(x) (as.numeric(Sys.Date())- as.numeric(x))/30)

It's returning all NAs

Upvotes: 0

Views: 64

Answers (1)

agstudy
agstudy

Reputation: 121598

You can use difftime:

dat$months.customer <- 
as.numeric(floor(difftime(Sys.Date(),dat$start.date,units="days")/30))

#   ID start.date months.customer
# 1  1 2015-04-09              16
# 2  2 2014-03-24              29
# 3  3 2016-07-01               1
# 4  4 2011-02-02              67

Upvotes: 2

Related Questions