R提取日期和时间信息 [英] R extract Date and Time Info

查看:476
本文介绍了R提取日期和时间信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的data.frame:

I have a data.frame that looks like this:

> df1
   Date         Name    Surname   Amount
2015-07-24      John     Smith     200

我想将日期"中的所有信息外推到新列中,所以我可以这样做:

I want to extrapolate all the infos out of the Date into new columns, so I can get to this:

> df2
   Date     Year  Month   Day    Day_w      Name    Surname   Amount
2015-07-24  2015    7     24    Friday      John     Smith     200

所以现在我想要有年,月,日和星期几.我怎样才能做到这一点?当我尝试首先使用as.Date将变量设为日期时,data.frame陷入混乱,并且Date全部变为NA(并且没有新列).感谢您的帮助!

So now I'd like to have Year, Month, Day and Day of the Week. How can I do that? When I try to first make the variable a date using as.Date the data.frame gets messed up and the Date all become NA (and no new columns). Thanks for your help!

推荐答案

也许有帮助:

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中的列顺序.

Afterwards you can rearrange the order of columns in df2as you desire.

这篇关于R提取日期和时间信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆