convert yyyymm on factor class to character class to be used with ChartSeries()

主宰稳场 提交于 2019-12-02 03:44:25

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"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!