How to append a vector as a row in a saved .RData

2019-08-08 05:35发布

The question a bit self explanatory but I should add that I do not want to load the file. I'm looking for something like append = TRUE for saving a .RData file . I want to do something like this:

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

Here is a reproducible example:

# 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)

Error in save(df, file = "mtcars.Rdata", append = TRUE) : object ‘TRUE’ not found

标签: r rdata
2条回答
男人必须洒脱
2楼-- · 2019-08-08 05:51

AFAIK, You'll have to load file to make changes in saved objects and then save those objects again. You can't even view names of objects stored without loading, let alone modifying contents.

If you want a one-line solution, you can write a function.

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
查看更多
霸刀☆藐视天下
3楼-- · 2019-08-08 05:55

SOmething like this may help for adding new objects to an existing .Rdata file:

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)
    }
}
查看更多
登录 后发表回答