2014-10-28 69 views
1

我知道我可以通过以下方式获得从Excel基于数字的日期(日以来,1899-12-30):[R日期基于Excel的数量

as.Date(41000, origin = "1899-12-30") 

,这将给我“2012- 04-01" 。然而,我想要相反。作为用户,我想输入一个日期作为字符串,并获得“1899年至1230年”以来的天数。

东西沿线

as.integer(as.Date('2014-03-01', origin="1899-12-30")) 

,我希望这将导致在41000,而不是在1970-01-01以来的的R天,这是15431.

也许这是愚蠢的,因为我知道

as.integer(as.Date('2012-04-01')) + 25569 

我只是想知道,如果有哪个做这样的功能:我可以通过编写类似手动添加的日子吗?

回答

4

我想你想difftime为:

difftime(as.Date('2012-04-01'), as.Date("1899-12-30")) 

## Time difference of 41000 days 
+0

我觉得这正是我想要的。感谢您的快速回复! – 2014-10-28 16:02:52

+2

或只是'as.Date('2012-04-01') - as.Date(“1899-12-30”)' – 2014-10-28 16:04:45

1

手工做吧,简单和更安全:

d0 <- as.Date('1899-12-30') 
d1 <- as.Date('2014-10-28') 

as.integer(d1 - d0) 
##[1] 41940 # This is interpreted by Excel as '2014-10-28' 

当然,你可以写一个函数来A R日期转换为Excel one:

convert_to_excel_date <- function(d) { 
    # Converts a R date value to an Excel date value 
    # 
    # Parameters: 
    # d: a R date object 
    d0 <- as.Date('1899-12-30') 
    return(as.integer(d - d0)) 
} 
# Example: 
# convert_to_excel_date(as.Date('2018-10-28'))