I have an object that I have created using the as.ts function in R, and now I would like a simple way to transform one of the variables and add it to the same ts object. So, for example
tsMloa <- ts(read.dta("http://www.stata-press.com/data/r12/mloa.dta"), frequency=12, start=1959)
tsMloa[, "meanLog"] <- tsMloa[,"log"] - mean(tsMloa[,"log"])
gives me a subscript out of bounds error. How can I get around this?
Firstly, you ought to consider adding
require(foreign)to your example code, as it’s necessary to run your code.I don’t know anything about
*.dtafiles or their formatting, but i can tell you that if you’d like to work with time series inR, you’d do well to look into thezooandxtsfamily of functions.With that in mind, try the following:
That should do what you are looking for — and it gives you a reason to look into the very good packages.
Doing it with
zoo— plus i’ve created a function to turn your integers into months.As i see it, your problem is with converting the timestamps in the source file to something R understands and can work with. I found this part of adapting to R especially tricky.
The above function will take your month-integers, and turn them into a
Dateobject. The resultant output will work with bothzooandxtsas theorder.byargument.If you need to change the origin date, just supply the second argument to the function — i.e.
otherDateString <- intToMonth(timeInts, "2011-01-01").