如何使用R将向量作为行附加到已保存的.RData文件中

时间:2015-11-16 17:53:39

标签: r rdata

问题有点自我解释,但我应该补充一点,我不想加载文件。我正在寻找append = TRUE之类的内容来保存.RData文件。我想做这样的事情:

save(df, file="mtcars.Rda",append = TRUE)

这是一个可重复的例子:

# load data
  data("mtcars")
  head(mtcars)

# save original DF
  save(mtcars, file="mtcars.Rdata")

# create another DF
  df <- mtcars

# append DF to a saved Rdata file
  save(df, file="mtcars.Rdata",append = TRUE)
  

保存时出错(df,file =“mtcars.Rdata”,append = TRUE):    找不到对象'TRUE'

2 个答案:

答案 0 :(得分:1)

AFAIK,您必须load文件才能对已保存的对象进行更改,然后再次保存这些对象。您甚至无法查看存储的对象名称而无需加载,更不用说修改内容了。

如果您想要一个单行解决方案,可以编写一个函数。

appendToFile <- function(newRow, savedFile){
    load(savedFile, new.env())
    df = rbind(df, newRow)
    save(df, file = savedFile)
}

df <- data.frame(x = 1:5, y = 6:10)
save(df, file = "file.RData")
appendToFile(c(50, 100), "file.RData")

# Check if changes are saved
load("file.RData")
tail(df, 3)
##   x   y
##4  4   9
##5  5  10
##6 50 100

答案 1 :(得分:0)

类似这样的方法可能有助于将新对象添加到现有的.Rdata文件中:

add_object_to_rda <- function(obj, rda_file, overwrite = FALSE) {
    .dummy <- NULL
    if (!file.exists(rda_file)) save(.dummy, file = rda_file)

    old_e <- new.env()
    new_e <- new.env()

    load(file = rda_file, envir = old_e)

    name_obj <- deparse(substitute(obj))   # get the name of the object

    # new_e[[name_obj]] <- get(name_obj)     # use this only outside a function
    new_e[[name_obj]] <- obj

    # merge object from old environment with the new environment
    # ls(old_e) is a character vector of the object names
    if (overwrite) {
        # the old variables take precedence over the new ones
        invisible(sapply(ls(new_e), function(x)
            assign(x, get(x, envir = new_e), envir = old_e)))
        # And finally we save the variables in the environment
        save(list = ls(old_e), file = rda_file, envir = old_e)
    }
    else {
        invisible(sapply(ls(old_e), function(x)
            assign(x, get(x, envir = old_e), envir = new_e)))
        # And finally we save the variables in the environment
        save(list = ls(new_e), file = rda_file, envir = new_e)
    }
}