Reputation: 27
Given a vector of tracker names, for example: datanames = c("A", "B", "C", "D", "E")
I use this vector to collect data from a .csv and put it into a list of dataframes, named after the tracker.
for (stocks in datanames)
{
stockdfs[[stocks]] = mycsv[mycsv$tracker == stocks,]
}
This works perfectly fine.
I am now trying to convert this list into a list containing xts objects so I can do some time series analysis on it. I therefore add:
row.names(stockdfs[[stocks]]) = stockdfs[[stocks]]$Date #xts requirement
##BELOW IS WHERE THE PROBLEM LIES##
stockxts[[stocks]] = as.xts(stockdfs[[stocks]])
stockinsampxts[[stocks]] = as.xts(stockdfs[[stocks]][0:2000,])
stockoutsampxts[[stocks]] = as.xts(stockdfs[[stocks]][2000:nrow(stockdfs[[stocks]]),])
print(stocks)
The problem is, when I try to view the xts object inside the list, I get:
Error in names[[i]] : subscript out of bounds
The weird thing is, I can still access the data from the console, such as print(stockxts[["A"]]).
Help is much appreciated, I am a bit of an R newbie! Thank you!
Upvotes: 0
Views: 531
Reputation: 23598
There are 2 ways of creating an xts object, one via creating row.names and the second by using the order.by option in the as.xts
function.
But you should realise that you are not removing the date column from your data. xts data is a matrix and if a date is included everything in the matrix is a character.
After your rownames statement you can do the following to remove the dates:
stockdfs[[stocks]]$Date <- NULL
and then stockxts[[stocks]] = as.xts(stockdfs[[stocks]])
will have the xts data in numeric form (as long as there are no other character values in the other columns).
You can see the difference in outcome when you remove the date or leave the date in the following example:
A <- data.frame(Date = seq(as.Date("2018-02-01"), as.Date("2018-02-05"), by = "day"),
val1 = seq(1:5))
# everything a character
as.xts(A, order.by = A$Date)
Date val1
2018-02-01 "2018-02-01" "1"
2018-02-02 "2018-02-02" "2"
2018-02-03 "2018-02-03" "3"
2018-02-04 "2018-02-04" "4"
2018-02-05 "2018-02-05" "5"
# Everything numeric
as.xts(A[, -which(names(A) == "Date")], order.by = A$Date)
[,1]
2018-02-01 1
2018-02-02 2
2018-02-03 3
2018-02-04 4
2018-02-05 5
Upvotes: 1