Marshall Feldman
2010-Mar-28 18:07 UTC
[R] Preserving both yearmon and numeric data in an xls object
Hi R gourmets,
I am trying to convert an HTML table into an xts object. The table has
six columns, with the data of interest in a single row with each cell
containing a long, \n-delimited character string. Initially, I work with
these strings as elements in a list. This is necessary because the
strings in each cell do not translate into a regular matrix with
equal-length columns. Once I fix the entries, I'm ready to convert them
into an xts object. The first two columns of the original table contain
dates, and I want them to be of type "yearmon" in the xts object. The
other four columns have numeric data.
Here's my problem. If I convert the list into a data frame on the way to
making it an xlt, the first two columns correctly keep the data as the
yearmon class, but the remaining columns are converted to character
class. Alternatively, if I convert the list into a matrix on the way to
making the xlt, all six columns become numeric; the first two columns
lose their yearmon class.
How can I make an xlt from a list, such that the first two columns are
yearmon and the last four are numeric?
Thanks.
Marsh Feldman
P.S. Here is some sample code:
> #... input has been converted to a list of length 6; each element
is a vector, but they themselves are of different length
> #... fix the 6 vectors to have equal length
> mylist[1:2] <- lapply(mylist[1:2], as.yearmon) # Convert
the first two elements into yearmon class
> #... Now try one of the following; tindex is the time index in
yearmon format
> myxts <- as.xts(as.data.frame(mylist), order.by=tindex) # this
makes columns 3-6 of myxts all have class = character
> myxts <- as.xts(matrix(unlist(mylist), ncol=6), order.by=tindex)
# this makes myxts entirely numeric
I even tried using the following statement afterwards but
had no luck
> myxts[,1] <- as.yearmon(myxts[,1])
[[alternative HTML version deleted]]
