Wednesday, January 3, 2018

Make a combined data frame with a source label using the list names


rbind.df.with.list.names <- function(obj)
{ 
    ## Purpose: Make a combined data frame with a source label using the list names. 
    ## Arguments:
    ##    obj: It is a list of data frames to be "rbind" together. 
    ## Return: a single combined data frame with all the sub data frames in "obj"
    ##         with an addtional column "SOURCE0" from the names of the list "obj",
    ##         and another addtional column "SOURCE1" that abbreviates "SOURCE0". 
    ## Author: Feiming Chen, Date:  2 Jan 2018, 11:00
    ## ________________________________________________

    o <- do.call(rbind, obj)
    o$SOURCE0 <- rep(names(obj), sapply(obj, nrow))
    o$SOURCE1 <- abbreviate(o$SOURCE0)
    o
}
if (F) {                                # Unit Test
    obj <- list(A = data.frame(x = 1:3), B = data.frame(x = 4:6))
    rbind.df.with.list.names(obj)
##     x SOURCE0 SOURCE1
## A.1 1       A       A
## A.2 2       A       A
## A.3 3       A       A
## B.1 4       B       B
## B.2 5       B       B
## B.3 6       B       B
}

No comments:

Post a Comment