R 提取日期和时间信息
R extract Date and Time Info
我有一个 data.frame 看起来像这样:
> df1
Date Name Surname Amount
2015-07-24 John Smith 200
我想将日期中的所有信息外推到新列中,这样我就可以做到这一点:
> df2
Date Year Month Day Day_w Name Surname Amount
2015-07-24 2015 7 24 Friday John Smith 200
现在我想要年、月、日和星期几。我怎样才能做到这一点?当我尝试首先使用 as.Date 使变量成为日期时,data.frame 变得混乱并且日期全部变为 NA(并且没有新列)。感谢您的帮助!
也许这有帮助:
df2 <- df1
dates <- strptime(as.character(df1$Date),format="%Y-%m-%d")
df2$Year <- format(dates, "%Y")
df2$Month <- format(dates, "%m")
df2$Day <- format(dates, "%d")
df2$Day_w <- format(dates, "%a")
之后您可以根据需要重新排列 df2
中的列顺序。
这里有一个简单高效的解决方案,使用 data.table
的 devel
版本及其新的 tstrsplit
函数,它将只执行一次拆分操作并更新您的数据集 到位.
library(data.table)
setDT(df1)[, c("Year", "Month", "Day", "Day_w") :=
c(tstrsplit(Date, "-", type.convert = TRUE), wday(Date))]
df1
# Date Name Surname Amount Year Month Day Day_w
# 1: 2015-07-24 John Smith 200 2015 7 24 6
请注意,我使用了工作日的数字表示,因为在 data.table
包中有一个高效的内置 wday
函数,但如果您愿意,可以轻松调整它确实需要使用 format(as.Date(Date), format = "%A")
来代替。
要安装开发版本,请使用以下命令
library(devtools)
install_github("Rdatatable/data.table", build_vignettes = FALSE)
我有一个 data.frame 看起来像这样:
> df1
Date Name Surname Amount
2015-07-24 John Smith 200
我想将日期中的所有信息外推到新列中,这样我就可以做到这一点:
> df2
Date Year Month Day Day_w Name Surname Amount
2015-07-24 2015 7 24 Friday John Smith 200
现在我想要年、月、日和星期几。我怎样才能做到这一点?当我尝试首先使用 as.Date 使变量成为日期时,data.frame 变得混乱并且日期全部变为 NA(并且没有新列)。感谢您的帮助!
也许这有帮助:
df2 <- df1
dates <- strptime(as.character(df1$Date),format="%Y-%m-%d")
df2$Year <- format(dates, "%Y")
df2$Month <- format(dates, "%m")
df2$Day <- format(dates, "%d")
df2$Day_w <- format(dates, "%a")
之后您可以根据需要重新排列 df2
中的列顺序。
这里有一个简单高效的解决方案,使用 data.table
的 devel
版本及其新的 tstrsplit
函数,它将只执行一次拆分操作并更新您的数据集 到位.
library(data.table)
setDT(df1)[, c("Year", "Month", "Day", "Day_w") :=
c(tstrsplit(Date, "-", type.convert = TRUE), wday(Date))]
df1
# Date Name Surname Amount Year Month Day Day_w
# 1: 2015-07-24 John Smith 200 2015 7 24 6
请注意,我使用了工作日的数字表示,因为在 data.table
包中有一个高效的内置 wday
函数,但如果您愿意,可以轻松调整它确实需要使用 format(as.Date(Date), format = "%A")
来代替。
要安装开发版本,请使用以下命令
library(devtools)
install_github("Rdatatable/data.table", build_vignettes = FALSE)