Search code examples
rdataframexts

Converting a single column Dataframe to XTS is losing column name


I have a situation where I need to convert a data frame object into XTS object. The first column of my data frame is always a date object and is always named "Date". However, i would not know apriori, whether my dataframe object has 1 column (excluding the date) or more columns.

The issue is this: When i try to convert the dataframe object into xts using xts(), the resulting XTS object has the correct column names when the dataframe object has more than 1 columns. BUT if it has only one data column (excluding the date), it loses its column name. See the code below.

dv <- as.Date(c("2010-01-31", "2010-02-28", "2010-03-31"))
DF <- data.frame(Date = dv, C1 = c(1,2,3), C2 = c(10,20,30))
DF.subset <- data.frame(Date = dv, C1 = c(1,2,3))


DF.TS <- xts(DF[,-1], order.by =dv)
DF.subset.TS <- as.xts(DF.subset[,-1], order.by =dv)



> head(DF.TS)
           C1 C2
2010-01-31  1 10
2010-02-28  2 20
2010-03-31  3 30

> head(DF.subset.TS)
           [,1]
2010-01-31    1
2010-02-28    2
2010-03-31    3

> colnames(DF.TS)
[1] "C1" "C2"
> colnames(DF.subset.TS)
NULL

Why am I losing the column name (and how to avoid losing it) in the second instance (DF.subset.TS)? Any help is highly appreciated please.


Solution

  • When you have only one column in the data the default nature is to drop it's dimensions and convert it into vector.

    DF.subset[,-1]
    #[1] 1 2 3
    

    To avoid that and keep dataframe as dataframe you can use drop = FALSE.

    DF.subset[,-1, drop = FALSE]
    
    #  C1
    #1  1
    #2  2
    #3  3
    

    Now using it in xts function.

    library(xts)
    DF.TS <- xts(DF[,-1, drop = FALSE], order.by =dv)
    DF.subset.TS <- as.xts(DF.subset[,-1, drop = FALSE], order.by =dv)
    
    colnames(DF.TS)
    #[1] "C1" "C2"
    colnames(DF.subset.TS)
    #[1] "C1"