Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
四舍五入日期与R最接近的年份_R_Date_Rounding - Fatal编程技术网

四舍五入日期与R最接近的年份

四舍五入日期与R最接近的年份,r,date,rounding,R,Date,Rounding,我想在最接近这个人的生日时把自己的年龄圆点。我该怎么做?我不想使用if语句和包。非常感谢 字符串比较是一种方法 birth.date <- as.POSIXct("1970-07-08") current.date <- as.POSIXct("2014-07-31") years <- as.integer(sub("-.*$", "", c(birth.date, current.date))) month.days <- sub("^\\d+-", "", c(b

我想在最接近这个人的生日时把自己的年龄圆点。我该怎么做?我不想使用if语句和包。非常感谢

字符串比较是一种方法

birth.date <- as.POSIXct("1970-07-08")
current.date <- as.POSIXct("2014-07-31")

years <- as.integer(sub("-.*$", "", c(birth.date, current.date)))
month.days <- sub("^\\d+-", "", c(birth.date, current.date))

diff(years) + order(month.days)[2] - 1

365.2424位表示闰年()。

一种方法是减去年份,如果生日还没有过,再减去1。使用
POSIXlt
对象比使用
Date
对象要简单一些,因为您可以提取数字,而不必使用多个
as.integer
s

calcAge <- function(dr,db)
{
    dr <- as.POSIXlt(dr)
    db <- as.POSIXlt(db)
    dr$year-db$year-(dr$mon<db$mon | (dr$mon==db$mon & dr$mday<db$mday))
}

calcAge(Sys.Date(), as.Date(c("1967-04-01","1991-08-12")))
[1] 47 22

calage
birth.date你能举个例子吗?假设你有一个出生日期:
06/29/90
,然后找到今天的年龄:
diff-Rime这是我做的,在这种情况下使用round()将是25,但如果结果是24.5,它也将是25,而不是24(24.5接近24岁生日)。初学者R,这是一个例子. 谢谢@FrancescVE
round(24.5)
在统计舍入(R使用)中实际上是24。James这是真的。对不起,谢谢你,巴克林!确切地说,这是我处理时间的问题。。。第一种方法还可以,但我不知道使用大DDBB是否会稍微慢一点。Thnaks!!!很乐意帮忙!不过,你应该选择@James的答案,它更高效、更优雅。我的字符串比较建议本质上是对他的解决方案的拙劣修改。
calcAge <- function(dr,db)
{
    dr <- as.POSIXlt(dr)
    db <- as.POSIXlt(db)
    dr$year-db$year-(dr$mon<db$mon | (dr$mon==db$mon & dr$mday<db$mday))
}

calcAge(Sys.Date(), as.Date(c("1967-04-01","1991-08-12")))
[1] 47 22
birth.date <- "2018-04-30"

library(lubridate) 
year(birth.date)