我有一个带有出生日期的数据框列和一个带有1200个日期(估值日期)的向量。我想计算1200个时期内每个出生日期的年龄。我有一个解决方案,但我认为这很奇怪。
年龄函数:
age <- function(born_date, valuation_date){
if(any(!inherits(born_date, c("POSIXt", "POSIXct", "POSIXlt", "Date"))) |
any(!inherits(valuation_date, c("POSIXt", "POSIXct", "POSIXlt", "Date"))))
stop("Born date or valuation date is not in POSIXt or Date format")
round(as.double(valuation_date - born_date)/365.25)
}
df $ FNACIMI中的生日:
df <- structure(list(FNACIMI = structure(c(-4216, -188, -4124, -2750,
-2113, -95, 3840, -3629, 2321, 1629, -7547, -2883, -9987, -5078,
-895, -848, 3069, -5134, -3778, -3647, -1573, 2156, -3250, -8277,
-2516, -1829, -2448, -4658, -5731, -3554), class = "Date"), PRIMA_ANUAL = c(360,
0, 0, 0, 0, 720, 720, 100, 1200, 1200, 0, 1020, 0, 0, 0, 2100,
0, 0, 1200, 3000, 0, 0, 0, 8000, 1500, 0, 360, 0, 0, 0)), .Names = c("FNACIMI",
"PRIMA_ANUAL"), row.names = c(NA, -30L), class = "data.frame")
我的解决方案是:
result <- sapply(1:1200, flowDates)
flowDates <- function(i) {
mapply(fluxDates, df$FNACIMI[1:30], i)
}
fluxDates <- function(x, y){
dates <- seq(as.Date("2017-08-31"), by = "month", length.out = 1200)
mapply(age, x, dates[y])
}
正如我们所看到的,在另一个mapply内部和一个sapply内部有一个mapply。还有更优雅的方式吗?
谢谢!