我目前正在尝试绘制价格差的时间序列图,然后添加带有回归的 abline。目前这只是一个 AR(1),因为我想在开始之前先弄清楚情节。
数据来自 .XLS 在 OpenOffice 中也是这样组织的
Date - Price1 - Price 2 - NA.(Empty)
01.01.1982 - 1.56 - 2.53 -
[...]
我正在阅读此内容
library(xlsx)
library(AER)
x<-read.xlsx("data.xlsx",1)
然后我像这样填充空列
x$NA.=(x$Price1-x$Price2)
所以我现在内存中有一个表可以生成这个 head()
Date Price1 Price2 NA.
1 1987-08-28 18.30 19.44 1.24
2 1987-08-31 18.65 19.75 1.12
(日期之前有一个索引列,我真的不需要它,因为我按日期绘制,但它在那里)
然后我就这么做了
plot(x$Date,x$NA.)
我得到了正确的情节。我对该绘图命令进行了一些修改,以获得正确的网格、轴、日期和线条等,但即使使用上面的简单绘图版本,问题也仍然存在,所以问题不在于我的编辑。
问题如下:
如果我现在尝试绘制一条线
abline(a=1,b=1,col="blue")
这不起作用。命令执行完毕,但不显示一行。但是:
abline(a=1,b=0,col="blue")
按预期工作并显示一条蓝色水平线。
我遇到的问题是我想将回归对象输入到图中,例如像这样
SPRC=zoo(x$NA.,x$Date)
SPRC2=lag(SPRC, -1)
SPRC=SPRC[2:length(SPRC)]
LMO<-lm(SPRC ~ SPRC2)
abline(a=LMO$coefficients[2],b=LMO$coefficients[1],col="red")
我想做的是一个简单的 AR 来测试。回归按预期工作,但 abline 不产生输出。
我还尝试在没有变量的情况下执行 abline - 它仅在 b=0 时才有效。我也尝试做一个
plot(SPRC)
然后是任何类型的 abline,但要么不显示,要么变成垂直线(!)。只有当b=0时它才变成水平线。
我想这与数据对象或输入有关,但我真的不明白为什么它不起作用。我还尝试了 Date 对象上的 as.Date ,但这并没有改变任何东西。所有其他绘图命令似乎都可以工作,例如添加自定义网格、par、定位器文本、轴等。如果我启动一个干净的 R session 并且几乎只输入上面的代码,就会出现问题。 我还尝试切换回归变量、a 和 b 值或绘图变量的顺序。还是不行
你能想象可能出现什么问题吗?
编辑:
我刚刚检查了数据类型 if typeof()。
typeof x 是“list”,其他一切都是“double”,即使我做了 x$Date<-as.Date(x$Date,"%d.%m.%Y")
编辑2: 我继续将文件保存为 csv 并使用 read.csv 读取它 然后我就这么做了
plot(x$Price1)
和
abline(a=40,b=1)
它所做的只是产生一条稍微顺时针旋转的垂直(!)线。 我的R坏了吗?
(我意识到价格的比例不对 - 价差约为 0。但即使 a=40,这条线也是相同的)
最佳答案
x<- read.table(text="Date Price1 Price2 NA.
28.08.1987 18.30 19.44 1.24
31.08.1987 18.65 19.75 1.12", sep="", header=TRUE)
x$Date <- as.Date(x$Date, "%d.%m.%Y")
plot(x$Date, x$NA.)
我的区域设置是法语,因此 x 标签代表周五到周一。
# If we're trying to find the actual coordinates of some points on the plot
# here is what we find:
locator()
$x
[1] 6449.495 6448.035 6450.967
$y
[1] 1.182379 1.186610 1.182908
# The x axis is running from 6448 to 6451 and here is the reason:
x$Date # Here is your date vector
[1] "1987-08-28" "1987-08-31"
as.numeric(x$Date) # And here it is converted in numerics
[1] 6448 6451 # Hence the values found on the plot with locator.
# The default origin for dates is the first of January, 1970
# 6448 is the number of days from that date to the 28th of August 1987.
# But you can still use regression tools:
lm(NA.~Date, data=x)->lmx
abline(lmx) # YOu don't actually need to break your lm object into its coefficients, abline recognize lm objects.
# And the same works with package zoo
library(zoo)
x<- read.table(text="Date Price1 Price2 NA.
28.08.1987 18.30 19.44 1.24
31.08.1987 18.65 19.77 1.12
01.09.1987 18.65 19.75 1.10", sep="", header=TRUE)
x$Date <- as.Date(x$Date, "%d.%m.%Y")
SPRC<-zoo(x$NA.,x$Date)
SPRC2<-lag(SPRC, -1)
SPRC<-SPRC[2:length(SPRC)]
LMO<-lm(SPRC ~ SPRC2)
plot(SPRC)
abline(LMO)
关于r - 奇怪的阿布林行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478875/