Convert data.frame to xts object and preserve types

天大地大妈咪最大 提交于 2019-12-03 10:09:23

问题


Is there a way to create an xts object from a data.frame and preserve data type? My numerics are being converted to character. This post from 2009 suggests merging columns into an existing xts: http://r.789695.n4.nabble.com/as-xts-convert-all-my-numeric-data-to-character-td975564.html

It wasn't clear whether that is the ONLY way to do this. Seems a bit of a hack and cumbersome for large data frames. I would think out-of-the-box xts would respect the datatypes.


回答1:


No, you can't. xts/zoo objects are a matrix with an index attribute and you can't mix types in a matrix.

We've considered creating an xts-data.frame class but a primary concern of xts is speed and memory efficiency. data.frames are not speed and memory efficient, so this hasn't been a priority.




回答2:


I had the same problem, my solution was to not include the time column when specifying the data object. As long as all the other columns are of the same type, there should be no problems.

i.e.

data <- xts(data[,2:6], order.by = data$time, unique = FALSE, tzone = "")

(data$time is the first column and is POSIXct so I'm excluding it. everything else is numeric)



来源:https://stackoverflow.com/questions/6550482/convert-data-frame-to-xts-object-and-preserve-types

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