gpt4 book ai didi

r - 将日期转换为数字

转载 作者:行者123 更新时间:2023-12-04 18:58:10 25 4
gpt4 key购买 nike

我有一堆日期:

dates
[1] "24/06/2010" NA NA NA "11/05/2005" NA "24/02/2006"
[8] NA NA NA "27/10/2008" "09/05/2009" NA NA
[15] "14/12/2008" "14/12/2008" NA "07/04/2009" NA

并且想要制作一个新的向量,其中日期转换为数字,NA 转换为 -1 值。我知道在Excel中日期是根据标准程序转换成数字的,这里我不知道。

因此,例如,如果我们将起始日期 01/01/2008 固定为数字 0 并从那里开始计数

24/06/2010 将是从开始日期算起的 905 天。

最佳答案

这是一种方法:

# the reference date
starting_date <- as.Date("2008-01-01")
# transform the character vector to a date vector and subtract the reference date
res <- as.Date(dates, "%d/%m/%Y") - starting_date
# replace NAs with -1
res[is.na(res)] <- -1

结果:
# Time differences in days
# [1] 905 -1 -1 -1 -965 -1 -676 -1 -1 -1 300 494 -1 -1 348
# [16] 348 -1 462 -1

关于r - 将日期转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com