应用函数以获取从今天开始的月份

Apply function to get months from today's date

我正在尝试在数据集中创建一个列,告诉我客户在公司工作的(大约)月数。

这是我目前的尝试:

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)

它返回所有 NA

您可以使用 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