[英]add a data frame to an existing rdata file
我是R的新手,將盡我所能使自己理解。 假設我有一個包含多個對象的現有rdata文件。 現在我要向其中添加一個數據框,我該怎么做? 我嘗試了以下方法:
write.data.loc <- 'users/Jim/Objects'
rdataPath <- 'users/Jim/Objects.Rda'
myFile<- read.csv("myFile.csv")
loadObjects <- load(rdataPath)
save(loadObjects,myFile,file=paste(write.data.loc,".Rda",sep=""))
但這似乎行不通嗎?
我不確定您的實際用例,但是如果必須將新對象“附加”到rda
文件中,則這是一種方法。 這種嘗試是通過巧妙的load
荷蘭國際集團一切從對象的rda
文件到一個新的environment
(有很多教程和討論使用和環境的相關指南,哈德利的“高級R”是一個做了很好的工作,我認為)。
第一步將所有對象加載到新的(空)環境中。 使用否則為空的環境非常有用,這樣我們可以使用ls
輕松地從中獲取所有對象。
e <- new.env(parent = emptyenv())
load("path/to/.rda", envir = e)
您要添加的對象應加載到環境中的變量中。 請注意,美元符號訪問看起來與list
相同,這使得(1)容易混淆兩者,以及(2)易於理解$
提供的命名索引。
e$myFile <- read.csv("yourFile.csv")
最后一部分,重新保存rda
文件,是一種間接方法。 ls(envir = e)
返回環境中所有對象的變量名。 這很好,因為save
可以處理對象或其名稱。
do.call("save", c(ls(envir = e), list(envir = e, file = "newsave.rda")))
要知道,這在技術上並不追加 data.frame到rda
文件,它已經結束了,寫rda
有一個新的,恰好包含所有以前的對象和新的data.frame文件。
我寫了這個解決方案,可以添加數據框,列表,矩陣或列表。 默認情況下,它將覆蓋現有對象,但可以使用overwrite=TRUE
進行反轉。
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.