¿Cómo actualizar una fila en un objeto XTS de varias columnas?

Given a single-column xts object, I can update a row like this:

library(xts)
a=xts(1:5,Sys.Date()+1:5)
b=xts(77:77,Sys.Date()+2)
a[index(b)]=b

But once I have 2+ rows it fails with "number of items to replace is not a multiple of replacement length":

a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
a[index(b)]=b

How should I update a single row in an xts object?

For the moment I have this hack:

a$x[index(b)]=b$x
a$y[index(b)]=b$y

¿Hay una mejor manera?

Resultado Esperado:

> a
            x  y
2012-12-24  1 11
2012-12-25 77 78
2012-12-26  3 13
2012-12-27  4 14
2012-12-28  5 15

preguntado el 23 de diciembre de 12 a las 09:12

2 Respuestas

The easiest way is to use a comma in your subsetting command:

a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
a[index(b),]=b

Respondido el 23 de diciembre de 12 a las 15:12

a[index(b),] <- b , here changes the first index of a and not where index(a) == index(b), isn't? - un estudio

@agstudy: it works fine for me using xts currently on CRAN (0.8-8). - Josué Ulrico

Thanks, I've confirmed it works. (I see I was confused by commas and brackets in R again!) - cocinero darren

@JoshuaUlrich I have same version. Maybe because we don't have the same time zone. I update my answer to show wwhat I have when I use your method. - un estudio

una solución es usar coredata, to manipulate matrix

    coredata(a)[index(a)==index(b)] <- coredata(b)

> a
            x  y
2012-12-24  1 11
2012-12-25 77 78
2012-12-26  3 13
2012-12-27  4 14
2012-12-28  5 15

I would prefer to use a[index(b),]=b as mentioned in the other answer , but for some reasons when I use it I don't have the same result. (It changes the first date not the second one)

 a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
> b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
> a[index(b),]=b
> a
            x  y
2012-12-23 77 78
2012-12-24  2 12
2012-12-25  3 13
2012-12-26  4 14
2012-12-27  5 15

con

> b
            x  y
2012-12-24 77 78

Respondido el 23 de diciembre de 12 a las 21:12

I can't reproduce your second case. I tried first with no TZ set, then with Sys.setenv(TZ = "UTC"). Can you show str(a) y str(b)? I'm running version 0.8-8 of xts, 1.7-9 of zoo, and 2.15.2 of R. - cocinero darren

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.