[英]Create xts object from CSV
我正在嘗試從CSV文件生成xts。 作為一個簡單的矢量,輸出看起來還可以,即Date
和Value
列分別是字符和數字。
但是,如果我想使其成為xts,則輸出似乎是可疑的,我想知道xts上最左邊的列的輸出是什么?
> test <- read.csv("Test.csv", header = TRUE, as.is = TRUE)
> test
Date Value
1 1/12/2014 1.5
2 2/12/2014 0.9
3 1/12/2015 -0.1
4 2/12/2015 -0.3
5 1/12/2016 -0.7
6 2/12/2016 0.2
7 7/12/2016 -1.0
8 8/12/2016 -0.2
9 9/12/2016 -1.1
> xts(test, order.by = as.POSIXct(test$Date), format = "%d/%m/%Y")
Date Value
0001-12-20 "1/12/2014" " 1.5"
0001-12-20 "1/12/2015" "-0.1"
0001-12-20 "1/12/2016" "-0.7"
0002-12-20 "2/12/2014" " 0.9"
0002-12-20 "2/12/2015" "-0.3"
0002-12-20 "2/12/2016" " 0.2"
0007-12-20 "7/12/2016" "-1.0"
0008-12-20 "8/12/2016" "-0.2"
0009-12-20 "9/12/2016" "-1.1"
我只是想設置一個Date
排序的xts,而不是左邊的神秘列。 我也嘗試過xts的as.Date
,但結果相同。
我建議您使用read.zoo
從CSV讀取數據,然后使用as.xts
將結果轉換為xts。
Text <- "Date,Value
1/12/2014,1.5
2/12/2014,0.9
1/12/2015,-0.1
2/12/2015,-0.3
1/12/2016,-0.7
2/12/2016,0.2
7/12/2016,-1.0
8/12/2016,-0.2
9/12/2016,-1.1"
z <- read.zoo(text=Text, sep=",", header=TRUE, format="%m/%d/%Y", drop=FALSE)
x <- as.xts(z)
# Value
# 2014-01-12 1.5
# 2014-02-12 0.9
# 2015-01-12 -0.1
# 2015-02-12 -0.3
# 2016-01-12 -0.7
# 2016-02-12 0.2
# 2016-07-12 -1.0
# 2016-08-12 -0.2
# 2016-09-12 -1.1
請注意,您將需要在實際通話中省略text = Text
,並用file = "your_file_name.csv"
替換它。
問題似乎是雙重的。 第一,您的一個呼叫中括號放錯了位置; 第二,最左邊的列是索引,使Date
列多余。
df <- read.table(text="
Date Value
1/12/2014 1.5
2/12/2014 0.9
1/12/2015 -0.1
2/12/2015 -0.3
1/12/2016 -0.7
2/12/2016 0.2
7/12/2016 -1.0
8/12/2016 -0.2
9/12/2016 -1.1",
header=TRUE)
df$Date <- as.Date(df$Date, format="%d/%m/%Y")
library(xts)
xts(df[-1], order.by=df[,1])
# Value
# 2014-12-01 1.5
# 2014-12-02 0.9
# 2015-12-01 -0.1
# 2015-12-02 -0.3
# 2016-12-01 -0.7
# 2016-12-02 0.2
# 2016-12-07 -1.0
# 2016-12-08 -0.2
# 2016-12-09 -1.1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.