繁体   English   中英

在 R 中将数据转换为日期、月份、年份

[英]Convert data to date, month, year in lubridate in R

我有一个带有日期列的dataframe ,该列名为dateDecision 它们的格式为1970/01/01 我正在尝试将日期拆分为yearmonthdate列。 我使用了以下代码

df %>% mutate(year = lubridate::year(dateDecision), 
                month = lubridate::month(dateDecision), 
                day = lubridate::day(dateDecision))

我收到一条错误消息,提示错误 in as.POSIXlt.character(x, tz = tz(x)): character string is not in a standard unambiguous format

当我使用 dput(head(df,10)) 时,这是 output

structure(list(term = c("1791", "1791", "1791", "1791", "1791", 
"1792", "1792", "1792", "1792", "1792"), dateDecision = c("8/3/1791", 
"8/3/1791", "8/3/1791", "8/3/1791", "8/3/1791", "8/11/1792", 
"8/11/1792", "8/11/1792", "8/11/1792", "8/11/1792"), decisionType = c("6", 
"6", "6", "6", "6", "8", "8", "8", "8", "8"), dateArgument = c("8/2/1791", 
"8/2/1791", "8/2/1791", "8/2/1791", "8/2/1791", "8/9/1792", "8/9/1792", 
"8/9/1792", "8/9/1792", "8/9/1792")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

我该如何解决?

您需要先使用 lubridate 将dateDecision列转换为日期

df %>% mutate(dateDecision=lubridate::mdy(dateDecision),
              year = lubridate::year(dateDecision), 
              month = lubridate::month(dateDecision), 
              day = lubridate::day(dateDecision))

首先使用anytime::anydate()库将dateDecision列转换为日期:

library(anytime)
    date <- "1970/01/01"
    anytime::anydate(date)
    [1] "1970-01-01"

然后运行你的变异。 您也可以使用 timetk 中的timetk tk_augment_timeseries_signature()并且仅使用 select 仅yearmonthdate列。

library(timetk)
library(tidyverse)

# make some reproducible data
dates <-
    seq(as.Date('2019-01-01'), as.Date('2019-12-31'), by = 'days') 

dates <- as_tibble(dates)

#add the time signature features including year, month, day, day of week, day of month, #day of year, hour, minute, second to the input data

dates %>% 
tk_augment_timeseries_signature()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM