简体   繁体   English

如何从Rdata文件分配数据帧

[英]How to assign a data frame from a Rdata file

I have a data.frame in the following directory "/..../1_5_setpoint.Rdata". 我在以下目录“ /..../1_5_setpoint.Rdata”中有一个data.frame。

The name of the data frame is "setpoint" and the name of the file is "1_5_setpoint". 数据帧的名称为“ setpoint”,文件的名称为“ 1_5_setpoint”。 I want to create a data.frame with the name "1_5_setpoint". 我想创建一个名称为“ 1_5_setpoint”的data.frame。 This is my code: 这是我的代码:

  assign("1_5_setpoint",  get(load("/..../1_5_setpoint.Rdata")))

The problem is that I end up having to data frames in memory: one called "setpoints" (I don't want this one) and one called "1_5_setpoint" (I want this one). 问题是,我最终不得不访问内存中的数据帧:一个称为“设定点”(我不想要这个),另一个称为“ 1_5_setpoint”(我想要这个)。

This could cause a problem if the data is very big. 如果数据很大,可能会导致问题。

Any suggestions? 有什么建议么?

It would be easier if you would save your data as RDS not Rdata , you could then simply load it to an object with a desired name: 如果将数据另存为RDS而不是Rdata会更容易,然后可以将其简单地加载到具有所需名称的对象中:

saveRDS(mtcars, "mtcars.rds")
cars <- readRDS("mtcars.rds")

Rdata files are used to store all objects you created, have a look at this explanation . Rdata文件用于存储您创建的所有对象,请看下面的说明 As discussed here RDS is batter solution for storing single objects. 如此处所述 RDS是用于存储单个对象的面糊解决方案。

@Konrad is correct about RDS being the right solution. @Ron是正确的解决方案,@ Konrad是正确的。 Sometimes, you don't have the option of getting an RDS file and you only get a .RData file. 有时,您无法选择获取RDS文件,而只能获取.RData文件。 In that case, the simplest method I know of is to load the data using a function and either return the only variable within or allow selection of the variable to return. 在那种情况下,我知道的最简单的方法是使用一个函数加载数据,然后返回其中的唯一变量,或者允许选择要返回的变量。

An example there could be: 一个例子可能是:

myLoad <- function(filename, variable) {
  tmp.env <- new.env()
  varnames <- load(filename, envir=tmp.env)
  if (missing(variable)) {
    ## Choose the variable name as the only variable in the file or
    ## give an error.
    if (length(varnames) == 1) {
      return(get(varnames, envir=tmp.env))
    } else {
      stop("More than one variable present in the file, please specify which variable to extract.  Choices are: ",
           paste(varnames, sep=", "))
    }
  } else {
    return(get(variable, envir=tmp.env))
  }
}

ls()
save(mtcars, file="mtcars.RData")
mtcars_1_5 <- myLoad("mtcars.RData")
identical(mtcars, mtcars_1_5)
ls()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM