簡體   English   中英

如何使用R將向量作為行添加到已保存的.RData文件中

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

這個問題有點自我解釋,但是我要補充一點,我不想加載文件。 我正在尋找類似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'

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

這樣的事情可能有助於將新對象添加到現有的.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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM