R - 从文本文件中读取时间数据

时间:2017-08-07 00:15:14

标签: r

嗨,谢谢你,

所以我当前正试图从我想尝试的文本文件中读取测试日期列表,并在带有一些测试值的图表上绘制(称为数量)。

我遇到的问题是,当从文件中读取时间时,它们无法正确读取。当我将它们绘制到图表上时,这些值非常扭曲和不正确,并且不会显示任何类似于日期的内容。

这是我的代码:

Frame <- read.table("....path.../Frame.txt")
Frame$Time <- as.Date(Frame$Time)
TheForecast <- naive(Frame)
plot(TheForecast, xlab="Time",ylab="Quantity",main="Stock Quantity vs Time",type='l')

我在文本文件中尝试了所有不同格式的日期,但是它们都会返回相同的问题或更糟糕的问题。 以下是我尝试过的内容:

Time <- c("01/01/2010", "07/02/2010", "08/03/2010", "02/04/2011", "11/05/2011", "12/06/2011", "06/07/2012", "08/30/2012", "04/16/2013", "03/18/2013", "02/22/2014", "01/27/2014", "12/15/2015", "09/28/2015", "05/04/2016", "11/07/2017", "09/22/2017", "04/04/2017")
Time <- c("2010-01-01", "2010-07-02", "2010-08-03", "2011-02-04", "2011-11-05", "2011-12-06", "2012-06-07", "2012-08-30", "2013-04-16", "2013-03-18", "2014-02-22", "2014-01-27", "2015-12-15", "2015-09-28", "2016-05-04", "2017-11-07", "2017-09-22", "2017-04-04")
Time <- c("1 January 2010", "7 February 2010", "8 March 2010", "2 April 2011", "11 May 2011", "12 June 2011", "6 July 2012", "30 August 2012", "16 April 2013", "18 March 2013", "22 February 2014", "27 January 2014", "15 December 2015", "28 September 2015", "4 May 2016", "7 November 2017", "22 September 2017", "4 April 2017")

这里是y(数量)轴的测试值,仅供参考:

Quantity <- c(5,3,8,4,0,5,2,7,4,2,6,8,4,7,8,9,4,6)

以下是阅读前文件的示例:

Time Quantity
1 2010-01-01 5
2 2010-07-02 3
3 2010-08-03 8
4 2011-02-04 4
5 2011-11-05 0
6 2011-12-06 5
7 2012-06-07 2
8 2012-08-30 7
9 2013-04-16 4
10 2013-03-18 2
11 2014-02-22 6
12 2014-01-27 8
13 2015-12-15 4
14 2015-09-28 7
15 2016-05-04 8
16 2017-11-07 9
17 2017-09-22 4
18 2017-04-04 6

谢谢。

2 个答案:

答案 0 :(得分:2)

naive函数需要类ts或时间序列的对象才能正确显示图形。

file_path <- paste0(getwd(),"/data/Frame.txt")
Frame <- read.table(file_path, stringsAsFactors = FALSE)
Frame$Time <- as.Date(Frame$Time, format = "%Y-%m-%d")

这是您失踪的一步:

Frame <- ts(Frame$Quantity, start = 1, end = NROW(Frame), frequency = 1)

然后继续进行其余的工作,你的时间表应该更准确:

library(forecast)
TheForecast <- naive(Frame)
plot(TheForecast, xlab="Time",ylab="Quantity",main="Stock Quantity vs Time",type='l')

enter image description here

答案 1 :(得分:1)

以下内容对我来说没问题:

## Your Data
df = read.table(text="Time Quantity
1 2010-01-01 5
2 2010-07-02 3
3 2010-08-03 8
4 2011-02-04 4
5 2011-11-05 0
6 2011-12-06 5
7 2012-06-07 2
8 2012-08-30 7
9 2013-04-16 4
10 2013-03-18 2
11 2014-02-22 6
12 2014-01-27 8
13 2015-12-15 4
14 2015-09-28 7
15 2016-05-04 8
16 2017-11-07 9
17 2017-09-22 4
18 2017-04-04 6",
header=TRUE, stringsAsFactors=FALSE)

## Convert string to date
df$Time = as.Date(df$Time, format="%Y-%m-%d")

plot(df, pch=20)

Plot with Dates