gpt4 book ai didi

r - 在 R 中去掉日期和时间,这样你就有了每个数字组件

转载 作者:行者123 更新时间:2023-12-02 06:26:51 25 4
gpt4 key购买 nike

我目前以这种格式将日期存储为一个因素:"01_03_2018 08-30-09"

我希望将每个组件剥离为数值(在 R 代码中)。

所以上面的日期是

day = 1
month = 3
year = 2018
hour = 8
minutes = 30
seconds = 9

注意:所有这些值都需要采用数字格式。

感谢任何帮助。

最佳答案

lubridate 包中的 dmy_hms() 包装变量可以产生您想要的结果。包中这些函数的优点是引用自 RDocumentation

These functions recognize arbitrary non-digit separators as well as no separator. As long as the order of formats is correct, these functions will parse dates correctly even when the input vectors contain differently formatted dates.

library(lubridate)

x <- "01_03_2018 08-30-09"

# dmy_hms specifies the order as day, month, year, hour, minute, second

y <- dmy_hms(x)
day(y)
# 1
month(y)
#3
year(y)
#2018
hour(y)
#8
minute(y)
#30
second(y)
#9

然后您可以将它们强制为您喜欢的类型。不过,您可能希望使用 typeof() 检查默认类型,如果默认类型已经是您想要的类型。

关于r - 在 R 中去掉日期和时间,这样你就有了每个数字组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509061/

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