在r中更改时间序列的原点

时间:2016-11-28 10:05:11

标签: r csv formatting time-series code-formatting

我在R中有一个时间序列,我想与之合作,从01-01-52到01-01-88。 (1952年至1988年)。 37次观察。

然而,当我在R中读到它时,我遇到的问题是01-01-52到01-01-68的观察被解释为在2052年等,而不是1952年。

如何强制R读取所有数据,从1952年到1988年?

链接到我的数据:https://www.dropbox.com/s/93foyc238skt3xj/AgricIndus.csv?dl=0

这是我用过的代码。你知道我需要用我的代码做什么来使它正确读取吗?

agri <- read.table("AgricIndus.csv",
                  sep = ",", header = TRUE, skip = 0,
                  stringsAsFactors = FALSE)


agri$time <- as.Date(agri$time, "%m-%d-%y")

agri.xts <- xts(agri[, 2:3], order.by = agri$time)

2 个答案:

答案 0 :(得分:1)

一种方式(黑客)可以是:

agri$time <- as.Date(paste0(substring(agri$time,1,6), '19', substring(agri$time,7,8)), 
                                                                          "%m-%d-%Y")
agri$time
# [1] "01-01-52" "01-01-53" "01-01-54" "01-01-55" "01-01-56" "01-01-57" "01-01-58" "01-01-59" "01-01-60" "01-01-61" "01-01-62" "01-01-63" "01-01-64" "01-01-65"
# [15] "01-01-66" "01-01-67" "01-01-68" "01-01-69" "01-01-70" "01-01-71" "01-01-72" "01-01-73" "01-01-74" "01-01-75" "01-01-76" "01-01-77" "01-01-78" "01-01-79"
# [29] "01-01-80" "01-01-81" "01-01-82" "01-01-83" "01-01-84" "01-01-85" "01-01-86" "01-01-87" "01-01-88"

答案 1 :(得分:0)

如果您可以确定您的时间序列是常规的,那么生成常规日期序列可能是最简单的:

agri$time <- seq.Date(as.Date("1952-01-01"),as.Date("1988-01-01"),by='years’)

另一个适用于不规则时间序列的简单解决方案是使用format = %m-%d-%Y(大写“Y”!)将您的数据读取为52到88年,并添加1900年:

df$time <- as.POSIXlt(as.Date(df$time,format = '%m-%d-%Y'))
df$time$year <-df$time$year + 1900
df$time <- as.Date(df$time)
df$time
 [1] "1952-01-01" "1953-01-01" "1954-01-01" "1955-01-01"
 [5] "1956-01-01" "1957-01-01" "1958-01-01" "1959-01-01"
 [9] "1960-01-01" "1961-01-01" "1962-01-01" "1963-01-01"
[13] "1964-01-01" "1965-01-01" "1966-01-01" "1967-01-01"
[17] "1968-01-01" "1969-01-01" "1970-01-01" "1971-01-01"
[21] "1972-01-01" "1973-01-01" "1974-01-01" "1975-01-01"
[25] "1976-01-01" "1977-01-01" "1978-01-01" "1979-01-01"
[29] "1980-01-01" "1981-01-01" "1982-01-01" "1983-01-01"
[33] "1984-01-01" "1985-01-01" "1986-01-01" "1987-01-01"
[37] "1988-01-01"