代码之家  ›  专栏  ›  技术社区  ›  R Yoda

通过类似于rbind的引用将data.table附加到另一个data.table

  •  2
  • R Yoda  · 技术社区  · 8 年前

    不返回组合结果

    有可能,但是 rbind rbindlist 新的结果对象,而不是附加到现有的data.table对象。

    library(data.table)
    
    dt1 <- data.table(a = 1, b = "hello")
    dt2 <- data.table(a = 2, b = "world")
    
    dt.all <- data.table::rbindlist(list(dt1, dt2))
    
    dt.all
    #    a     b
    # 1: 1 hello
    # 2: 2 world
    
    
    dt.append <- function(x1, x2) {
      x1 <- data.table::rbindlist(list(x1, x2))  # does not change the outer data.table!
      invisible()
    }
    
    dt.append(dt1, dt2)
    
    dt1   # I would like to see both rows here
    #    a     b
    # 1: 1 hello
    
    1 回复  |  直到 8 年前
        1
  •  3
  •   akrun    8 年前

    dt.append <- function(x1, x2) {
      obj <- deparse(substitute(x1)) # get the actual object name as a string
      assign(obj, value = data.table::rbindlist(list(x1, x2)), envir = .GlobalEnv)
    
     }
    
    dt1
    #   a     b
    #1: 1 hello
    #2: 2 world