Home > Net >  rbind not keeping header names
rbind not keeping header names

Time:01-20

I'm fairly new to R, I feel like this is a basic question but I haven't been able to fix it.

I have the following code, where events_b an empty dataframe with the same headers as events, and cuts is a vector of POSIXct values.

events_b <- events[0,]
events_b <- rbind(events_b,
                     c(event$id[1],  event$start[1], cut[1]),
                     c(eventos$id[1], cut[1], as.POSIXct(event$start[1]))

However, when I do this, the headers from events_b (originally from events) are replaced with what looks like the column vector (ex, instead of "id", I'm getting "c..001....002" as a column header)

Is there a way of keeping the column headers? I'm going to put this code inside a loop, so the rbind will keep adding rows to events_b, but it's important for it to start out empty.

CodePudding user response:

The issues sstems from the source of rbind.data.frame. The code will iteratively try to find all zero-length arguments and silently removes them. This is done without name preservation of the first argument and is documented in the "Data frame methods" section of help(rbind). From the help page:

The rbind data frame method first drops all zero-column and zero-row arguments

To keep the names, either make certain the first row is not of zero length or add names(event_b) <- names(event) at the end of your code.

The source code for this behaviour is indicated below:

> rbind.data.frame
function (..., deparse.level = 1, make.row.names = TRUE, stringsAsFactors = FALSE, 
    factor.exclude = TRUE) 
{
... # more code
    allargs <- list(...)
    allargs <- allargs[lengths(allargs) > 0L] # drop everything of column length zero
    if (length(allargs)) {
        nr <- vapply(allargs, function(x) if (is.data.frame(x)) 
            .row_names_info(x, 2L)
        else if (is.list(x)) 
            length(x[[1L]])
        else length(x), 1L)
        if (any(n0 <- nr == 0L)) {
            if (all(n0)) 
                return(allargs[[1L]])
            allargs <- allargs[!n0] # drop everything of row-length 0
        }
    }
... # more code
}

Looking at the first couple of lines of the source of rbind.data.frame

  • Related