Efficient alternatives to merge for larger data.frames R

前端 未结 3 1889
花落未央
花落未央 2020-12-02 11:27

I am looking for an efficient (both computer resource wise and learning/implementation wise) method to merge two larger (size>1 million / 300 KB RData file) data frames.

3条回答
  •  难免孤独
    2020-12-02 12:02

    Here's the obligatory data.table example:

    library(data.table)
    
    ## Fix up your example data.frame so that the columns aren't all factors
    ## (not necessary, but shows that data.table can now use numeric columns as keys)
    cols <- c(1:5, 7:10)
    test[cols] <- lapply(cols, FUN=function(X) as.numeric(as.character(test[[X]])))
    test[11] <- as.logical(test[[11]])
    
    ## Create two data.tables with which to demonstrate a data.table merge
    dt <- data.table(test, key=names(test))
    dt2 <- copy(dt)
    ## Add to each one a unique non-keyed column
    dt$X <- seq_len(nrow(dt))
    dt2$Y <- rev(seq_len(nrow(dt)))
    
    ## Merge them based on the keyed columns (in both cases, all but the last) to ...
    ## (1) create a new data.table
    dt3 <- dt[dt2]
    ## (2) or (poss. minimizing memory usage), just add column Y from dt2 to dt
    dt[dt2,Y:=Y]
    

提交回复
热议问题