Search code examples
rdplyrxts

How to bind multiple data frames with rows named as dates using bind_rows? I’m getting error: Error in bind_rows_(x, .id) : Argument 1 must have names


I have multiple data frames of xts class, collected in a list that I'd like to combine to one data frame using bind_rows but keeping the row names.

library(xts)
library(dplyr)

data <- data.frame(a = c(1, 2, 3),
                   b = c(4, 5, 6))

dates <- as.Date(c("2019-01-31", "2019-02-28", "2019-03-31"))

Assume that having below three xts data frames is the starting point:

ts_data_1 <- as.xts(data[1, ], order.by = dates[1])
ts_data_2 <- as.xts(data[2, ], order.by = dates[2])
ts_data_3 <- as.xts(data[3, ], order.by = dates[3])

ts_list <- list(ts_data_1, ts_data_2, ts_data_3)

bind_rows(ts_list)

This doesn't work however and returns error: "Error in bind_rows_(x, .id) : Argument 1 must have names".

I suppose that this error occurs because of the named rows. I wouldn't want to move them to new a column or get rid off though. Is there a neat way to do this?


Solution

  • as the error states, it requires a data.frame/tibble etc. One option is to create a tibble

    library(tibble)
    map_df(ts_list, as_tibble)
    

    NOTE: With the above, the row names info (index of xts) would be lost because tibble doesn't support custom rownames

    NOTE2: the xts object have column names

    colnames(ts_list[[1]])
    #[1] "a" "b"
    

    and it is not the source of error

    If we also do it on another example, gets the same error

    bind_rows(list(matrix(1:5, dimnames = list(NULL, "a")),
        matrix(1:10, dimnames = list(NULL, "a"))))
    

    Error: Argument 1 must have names

    Note that both the matrices have the column names. It is not related to column names, but


    A base R option would be

    do.call(rbind, ts_list)