I read a CSV file using read.csv()
command and I want to convert into xts and graph with chartSeries()
.
I changed into a matrix by doing:
MyData <- as.matrix(MyData)
When I convert to xts using
MyData_xts <- xts(MyData[,-1], order.by=as.POSIXct(MyData[,1]))
I get the following error message:
Error in as.POSIXlt.character(as.character(x), ...) :
character string is not in a standard unambiguous format
The column that has my index is in the yyyymm format. I've read that that may be a problem, but I haven't been able to find a way around it.
EDIT 1
The CSV read before converting to matrix looks like this. All of the rows are factors class:
X |Mkt.RF|SMB
------|------|---
196307|-0.39 |-.046
196308|5.07 |-0.81
196308|-1.57 |-.048
You should use read.zoo
to import your CSV directly into a zoo object. If you want, you can use as.xts
to convert the zoo object to xts. You should also use a yearmon
index, since your index only has years and months.
Text <- "X,Mkt.RF,SMB
196307,-0.39,-0.046
196308, 5.07,-0.810
196309,-1.57,-0.048"
# function adapted from examples in ?read.zoo
z <- read.zoo(text=Text, header=TRUE, sep=",",
FUN=function(x) as.yearmon(format(x), "%Y%m"))
z
# Mkt.RF SMB
# Jul 1963 -0.39 -0.046
# Aug 1963 5.07 -0.810
# Sep 1963 -1.57 -0.048
Since you do not provide any data, I will use a small test example that matches your description. I do not think that as.POSIXct
will work without specific days. You can make this work by using the first day of each month.
x = c("201701", "201702", "201703")
xt = as.POSIXct(paste(x, "01", sep=""), format="%Y%m%d")
xts(xt, order.by=xt)
[,1]
2017-01-01 1483246800
2017-02-01 1485925200
2017-03-01 1488344400
Updated:
I see that you have now provided data and say that you are getting NAs. I am using the data that you provided, reading it as a csv, processing it with my code and not getting NAs. Please look again at this version of the code.
Input = read.csv(text="X,Mkt.RF,SMB
196307,-0.39 ,-.046
196308,5.07 ,-0.81
196308,-1.57 ,-.048",
header=TRUE, stringsAsFactors=FALSE)
library(xts)
Input$xt = as.POSIXct(paste(Input$X, "01", sep=""), format="%Y%m%d")
xts(Input, order.by=Input$xt)
X Mkt.RF SMB xt
1963-07-01 "196307" "-0.39" "-0.046" "1963-07-01"
1963-08-01 "196308" " 5.07" "-0.810" "1963-08-01"
1963-08-01 "196308" "-1.57" "-0.048" "1963-08-01"
来源:https://stackoverflow.com/questions/42616109/convert-yyyymm-on-factor-class-to-character-class-to-be-used-with-chartseries