2016-08-16 94 views
0

我試圖在數據集中創建一個列,告訴我客戶與公司在一起的(近似)月數。應用函數從今天的日期獲取月份

這是我目前的嘗試:

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) 

它返回所有的NAS

+0

'(as.numeric(Sys.Date()) - 作爲.nu​​meric(dat $ start.date))/ 30' – r2evans

+0

其他答案很好,你的問題是當你想要'sapply'和'dat [,2]'時使用'apply'和'dat [2]'' – TomNash

回答

2

您可以使用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 
相關問題