如何确定 as.Date, R 中原点的正确参数 [英] How to determine the correct argument for origin in as.Date, R

查看:20
本文介绍了如何确定 as.Date, R 中原点的正确参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有一个数据集,其中包含格式为 yyyy/mm/dd 的日期列.我正在尝试使用 as.Date 将这些日期转换为 R 中的日期对象.但是,我似乎无法找到将原点输入到 as.Date 的正确参数.以下代码是我一直在尝试的示例.我使用的是 Excel 中的 CSV 文件,因此我使用了 origin="1899/12/30 基于我看过的其他网站.

I have a data set in R that contains a column of dates in the format yyyy/mm/dd. I am trying to use as.Date to convert these dates to date objects in R. However, I cannot seem to find the correct argument for origin to input into as.Date. The following code is an example of what I have been trying. I am using a CSV file from Excel, so I used origin="1899/12/30 based on other sites I have looked at.

> as.Date(2001/04/26, origin="1899/12/30")

 [1] "1900-01-18"

但是,这不起作用,因为输入日期 2001/04/26 返回为1900-01-18".我需要将日期转换为日期对象,以便我可以将日期转换为儒略日期.

However, this is not working since the input date 2001/04/26 is returned as "1900-01-18". I need to convert the dates into date objects so I can then convert the dates into julian dates.

推荐答案

您可以是带有数值或字符值的 as.Date.当你在 R 中输入 2001/04/26 时,就是在做除法并得到 19.24(一个数值).数值需要一个原点,您提供的数字是该原点的偏移量.所以你离你的原点还有 19 天,即1900-01-18".像 2001 年 4 月 26 日这样的日期是

You can either is as.Date with a numeric value, or with a character value. When you type just 2001/04/26 into R, that's doing division and getting 19.24 (a numeric value). And numeric values require an origin and the number you supply is the offset from that origin. So you're getting 19 days away from your origin, ie "1900-01-18". A date like Apr 26 2001 would be

as.Date(40659, origin="1899-12-30")
# [1] "2011-04-26"

如果 Excel 中的日期看起来像"日期,则它们很可能是字符值(或因子).要使用 as.Date() 将字符值转换为日期,请指定格式.这里

If your dates from Excel "look like" dates chances are they are character values (or factors). To convert a character value to a Date with as.Date() you want so specify a format. Here

as.Date("2001/04/26", format="%Y/%m/%d")
# [1] "2001-04-26"

有关特殊 % 变量的详细信息,请参阅 ?strptime.现在,如果您使用 read.table 或其他内容将数据读入 data.frame,则您的变量可能是一个因素.如果是这种情况,您将需要使用 '

see ?strptime for details on the special % variables. Now if you're read your data into a data.frame with read.table or something, there's a chance your variable may be a factor. If that's the case, you'll want do convert to character with'

as.Date(as.character(mydf$datecol), format="%Y/%m/%d")

这篇关于如何确定 as.Date, R 中原点的正确参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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