How to append a vector as a row in a saved .RData file with R

你说的曾经没有我的故事 提交于 2019-12-11 09:44:04

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/33741620/how-to-append-a-vector-as-a-row-in-a-saved-rdata-file-with-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!