Problem with cbind xts objects

Hi Guys,

I'm trying to manage xts objects in particular merge xts objects.

I built a first xts object called stock, and I build performance indicator RDP_5 (a new xts object)

I create a new xts object y1 based on RDP_5.

When I truy to combine the 2 objects: RDP_5 and y1 in xts object called xts1. It doesn't wok. The time indexes are the same. A warning message appears:
In merge.xts(..., all = all, fill = fill, suffixes = suffixes)
NAs introduced by coercion

I would appreciate if someone could shed me some insights to handle my issue as I am new to R

Best :smile:

library(pdfetch)
library(xts)

stock<-pdfetch_YAHOO("FP.PA", from = as.Date("2015-01-01"), to = as.Date("2019-03-31"))
colnames(stock)<- c("open","high","low", "close", "adjclose", "volume")
dates <- index(stock)
nb=nrow(stock)

#calculus
RDP_5=matrix(NA,nb,1)
RDP_5=xts(RDP_5, time(stock))
RDP_5=100*diff(stock[,4], lag=5, arithmetic=FALSE, log=TRUE)
colnames(RDP_5)<-"RDP5"

y1=matrix(NA,nb)
y1=xts(x=y1, order.by=dates)

for (i in 1:nb){
  temp=RDP_5[i]
  y1[i]=ifelse(-temp>4,"low", "high")
}

xts1=cbind(RDP_5, y1)

Not to be rude, but I won't run any code example which fetches things from the internet. It's a rule of thumb for security reasons. In this case, it also introduces unnecessary complexity for a minimal and reproducible example.

But the rest of the code shows the problem: you're mixing types. RDP_5 is numeric, and y1 is character. When you cbind them, you're forcing them to become a single type. R will implicitly coerce the values to be the same, but it's better to explicitly do it yourself.

Example:

a <- xts(1:3, Sys.Date() + 1:3)
a
#            [,1]
# 2019-02-05    1
# 2019-02-06    2
# 2019-02-07    3

b <- xts(letters[1:3], Sys.Date() + 1:3)
b
#            [,1]
# 2019-02-05 "a" 
# 2019-02-06 "b" 
# 2019-02-07 "c"

combined <- cbind(a, b)
# Warning message:
# In merge.xts(..., all = all, fill = fill, suffixes = suffixes) :
#   NAs introduced by coercion

combined
#            ..1 ..2
# 2019-02-05   1  NA
# 2019-02-06   2  NA
# 2019-02-07   3  NA

So cbind is coercing the character values to be numeric. In your example, it doesn't know what number to use for "low" and "high", so it replaces them with NA.

Usually, when combining numeric and character values, base R packages will coerce the result to be character. However, cbind(<xts object>, ...) will use the special cbind.xts method from the xts package. So it's up to the xts package to handle coercion. And it seems it handles it differently than the base R standard.

Thank you for comments. It makes sense.
The package xts must handle coercion.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.