-1

I have this .txt file: http://pastebin.com/raw.php?i=0fdswDxF

First column (Date) shows date in month/day So 0601 is the 1st of June

When I load this into R and I show the data, it removes the first 0 in the data. So when loaded it looks like:

601
602

etc For 1st of June, 2nd of June

For the months 10,11,12, it remains unchanged.

How do I change it back to 0601 etc.?

What I am trying to do is to change these days into the day of the year, for instance, 1st of January (0101) would be 1, and 31st of December would be 365.

There is no leap year to be considered.

I have the code to change this, if my data was shown as 0601 etc, but not as 601 etc.

copperNew$Date = as.numeric(as.POSIXct(strptime(paste0("2013",copperNew$Date), format="%Y%m%d")) - 
                              as.POSIXct("2012-12-31"), units = "days")

Where Date of course is from the file linked above.

Please ask if you do not consider the description to be good enough.

4

5 回答 5

4
d<-as.Date("0201", format = "%m%d")
strftime(d, format="%j")
#[1] "032"

首先,您解析您的字符串并获取代表您的日期的 Date 对象(请注意,它将添加当前年份,因此如果您想计算某个特定年份的天数,请将其添加到您的字符串中:)as.Date("1988-0201", format = "%Y-%m%d")

函数strftime会将您的 Date 转换为 POSIXlt 对象并返回一年中的某一天。如果您希望结果是一个数值,您可以这样做:(as.numeric(strftime(d, format = "%j"))感谢 Gavin Simpson)

于 2013-05-07T19:24:13.810 回答
4

您可以colClassesread.table函数中使用,然后转换为POSIXlt并提取年份日期。你把这个过程复杂化了。

copperNew <- read.table("http://pastebin.com/raw.php?i=0fdswDxF", header=TRUE,
colClasses=c("character", "integer", rep("numeric", 3)))

tmp <- as.POSIXlt( copperNew$Date, format='%m%d' )
copperNew$Yday <- tmp$yday

as.POSIXct函数能够解析没有年份的字符串(假设为当前年份)并为您计算一年中的哪一天。

于 2013-05-07T20:48:19.140 回答
3

将其转换为POSIXlt使用不是闰年的年份,然后访问该yday元素并添加 1(因为yday1 月 1 日为 0)。

strptime(paste0("2011","0201"),"%Y%m%d")$yday+1
# [1] 32

从开始到结束:

x <- read.table("http://pastebin.com/raw.php?i=0fdswDxF",
  colClasses=c("character",rep("numeric",5)), header=TRUE)
x$Date <- strptime(paste0("2011",x$Date),"%Y%m%d")$yday+1
于 2013-05-07T19:22:45.863 回答
0

这个对我有用:

copperNew <- read.table("http://pastebin.com/raw.php?i=0fdswDxF", 
                         header=TRUE, sep=" ", colClasses=c("character", 
                                                            "integer", 
                                                            rep("numeric", 3)))

copperNew$diff = difftime(as.POSIXct(strptime(paste0("2013",dat$Date), 
                                     format="%Y%m%d", tz="GMT")),  
                          as.POSIXct("2012-12-31", tz="GMT"), units="days")

我必须指定时区(tzas.POSIXct 中的参数),否则我要减去的向量有两个不同的时区,因此不是整数天。

于 2013-05-07T20:41:07.763 回答
0

用哪种语言?

如果它是 C#、Java 或 Javascript 之类的东西,我会按照以下步骤操作:

1-) 从该列解析一对整数;2-) 创建一个日期时间变量,其日期和月份取自第一步的整数。将年份设置为某个固定值或当前年份。3-) 创建另一个 datetime 变量,其日期与步骤 2 中的日期是同一年的 2 月 1 日。

天数是日期时间变量之间的天数差 + 1 天。

于 2013-05-07T19:15:04.510 回答