Search code examples
rsubsetxtszoo

How do I subset a row of an xts object as a named vector?


I am unable to figure out how to subset a row from an xts object and have a result that is a named vector. Here is an example. Make a toy xts object:

x <- c("a","b","c")
z <- as.data.frame(matrix(data = c(1,2,3,4,5,6,7,8,9), nrow = 3))
colnames(z) <- x
z_xts <- xts(z, order.by = as.Date(17897:17899))

Here is that example xts object, z_xts:

           a b c
2019-01-01 1 4 7
2019-01-02 2 5 8
2019-01-03 3 6 9

I would like to subset columns a and b of row 2 of z_xts, for example:

sub_z <- z_xts[2, ][1, c("a","b”)]

This gives:

           a b
2019-01-02 2 5

who is class “xts” “zoo”. But, I want a named vector of class numeric. I’ve tried everything and the closest I can get is:

sub_z <- as.numeric(coredata(z_xts[2, ][1, c("a","b")]))

which gives:

[1] 2 5

which is class “numeric” but it has lost the column names. What I really want is:

a b 
2 5

How does one do that??


Solution

  • How about this

    cols <- c("a", "b")
    v <- setNames(as.numeric(z_xts[2, cols]), cols)
    v
    #a b
    #2 5
    

    v is named vector

    str(v)
    # Named num [1:2] 2 5
    # - attr(*, "names")= chr [1:2] "a" "b"