Note that there are some explanatory texts on larger screens.

plurals
  1. POR: Converting data frame (mixed factor and numeric) to XTS in R
    primarykey
    data
    text
    <p>When converting a data frame with mixed factor and numeric columns to an xts, all of my data gets converted to strings. This isn't a problem with the factors, but it's extremely annoying with the numerics. Is there a workaround?</p> <p>For example:</p> <pre><code>&gt; x marketTimestamp price id 1 2010-12-17 11:38:31.100 83.89 b-0 2 2010-12-17 11:38:31.100 83.88 b-1 3 2010-12-17 11:38:31.100 83.87 b-2 4 2010-12-17 11:38:31.300 83.91 o-0 5 2010-12-17 11:38:31.300 83.92 o-1 6 2010-12-17 11:38:31.300 83.93 o-2 &gt; as.xts(x[,-1],as.POSIXct(x[,1])) price id 2010-12-17 11:38:31 "83.89" "b-0" 2010-12-17 11:38:31 "83.88" "b-1" 2010-12-17 11:38:31 "83.87" "b-2" 2010-12-17 11:38:31 "83.91" "o-0" 2010-12-17 11:38:31 "83.92" "o-1" 2010-12-17 11:38:31 "83.93" "o-2" </code></pre> <p>Ideally I want the first column to remain numeric, whilst the second is converted to a string. The solution needs to be fully automated, as I am working with data sets with a large number of columns, and I can't always predict which ones will be factor and which will be numeric.</p> <p>--</p> <p>Edit:</p> <p>I've tried to get around this problem by defining the following function:</p> <pre><code>to.xts &lt;- function(data) { timestamp &lt;- as.POSIXct(data[,1]) coredata &lt;- data[,-1] headers &lt;- names(coredata) data.type &lt;- c() for (header in headers) { data.type[headers==header] &lt;- class(coredata[[header]]) } data.factor &lt;- xts(coredata[,data.type=="factor"],timestamp) data.numeric &lt;- xts(coredata[,data.type=="numeric"],timestamp) data.xts &lt;- cbind(data.factor,data.numeric) } </code></pre> <p>but when merging the two XTS objects, the string data is converted to NAs:</p> <pre><code>&gt; x id side 2010-12-17 11:38:31 "b-0" "BID" 2010-12-17 11:38:31 "b-1" "BID" 2010-12-17 11:38:31 "b-2" "BID" &gt; y price 2010-12-17 11:38:31 83.89 2010-12-17 11:38:31 83.88 2010-12-17 11:38:31 83.87 &gt; merge(x,y) id side price 2010-12-17 11:38:31 NA NA 83.89 2010-12-17 11:38:31 NA NA 83.88 2010-12-17 11:38:31 NA NA 83.87 Warning message: In merge.xts(x, y) : NAs introduced by coercion </code></pre> <p>Is this a known problem with the XTS package, or am I doing something wrong?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload