1

I'm using R 3.0.2 and I loaded a csv into a dataframe that I want to convert to xts format.

my data looks something like this

head(data)
          V1     V2      V3      V4      V5      V6      V7      V8      V9
1 1999-01-04 1.1812 1.18120 1.18120 1.18120 1.18120 1.18120 1.18120 1.18120
2 1999-01-05 1.1760 1.17860 1.17860 1.17860 1.17860 1.17860 1.17860 1.17860
3 1999-01-06 1.1636 1.17360 1.17360 1.17360 1.17360 1.17360 1.17360 1.17360
4 1999-01-07 1.1672 1.17200 1.17200 1.17200 1.17200 1.17200 1.17200 1.17200
5 1999-01-08 1.1554 1.16868 1.16868 1.16868 1.16868 1.16868 1.16868 1.16555
6 1999-01-11 1.1534 1.16613 1.16613 1.16613 1.16613 1.16613 1.16312 1.15990

following advice from this post I tried to convert the row name as follows

rownames(data) = data[1]

however I get the following error which I can't find my way around

Error in `row.names<-.data.frame`(`*tmp*`, value = value) : 
  invalid 'row.names' length
Community
  • 1
  • 1
pyCthon
  • 11,746
  • 20
  • 73
  • 135
  • 2
    Try `rownames(data) = data[, 1]`. – A5C1D2H2I1M1N2O1R2T1 Oct 03 '13 at 02:25
  • And, Dirk's answer there is the best one to follow if your end goal is conversion to xts. `dataxts <- xts(data[,-1], order.by=data[,1])`. That basically translates to "use the data from all columns except the first, ordered by the time values found in the first column". – A5C1D2H2I1M1N2O1R2T1 Oct 03 '13 at 02:27
  • @AnandaMahto dirks answer gave me an error, `order.by requires an appropriate time-based object` – pyCthon Oct 03 '13 at 02:29
  • 2
    Well you need to convert your first column first -- `as.Date()` say -- but beware of the pitfall of `stringsAsFactors` etc. But there are dozens of 'how do I create an xts' posts around. – Dirk Eddelbuettel Oct 03 '13 at 02:32
  • @pyCthon, please post your edit as an answer (and *accept* it) to indicate to others that the problem has been solved. – A5C1D2H2I1M1N2O1R2T1 Oct 03 '13 at 02:45

1 Answers1

2

based off the very generous comments here is a simple solution

rownames(data) <- as.Date(data[,1]) 
dataxts <- xts(data[,-1], order.by=data[,1])
pyCthon
  • 11,746
  • 20
  • 73
  • 135
  • 3
    I think you want `data[,1] <- as.Date(data[,1])`, possibly with an `as.character(data[,1])` depending on how you read the data. Making rownames a Date object does not make the first column one, and that is what you use here. – Dirk Eddelbuettel Oct 03 '13 at 02:51
  • 3
    Perhaps for your benefit, you can explore a little and try to understand *why* the solution I shared in the comments work. See for instance `str(data[1])` as opposed to `str(data[[1]])` or `str(data[, 1])`. Also note from `?xts` that "`order.by`" is *a corresponding vector of unique times/dates*. – A5C1D2H2I1M1N2O1R2T1 Oct 03 '13 at 08:12