简体   繁体   English

在函数内部加载Rdata文件

[英]Loading a Rdata file inside a function

I have a function to which I have to pass the dataset. 我有一个必须将数据集传递给的函数。

loading <- function(dataset){
merchants <- load(dataset)
return(merchants)
}

But when I use the loading function it returns a character vector 但是当我使用加载函数时,它返回一个字符向量

loading("capital.Rdata")
"capital"

How do I load the data inside the function? 如何在函数内加载数据?

The load() command doesn't return the object stored in the RData file. load()命令不会返回存储在RData文件中的对象。 Instead, it returns a character vector that lists the names of all the objects that were loaded from the Rdata file. 而是返回一个字符向量,该向量列出从Rdata文件加载的所有对象的名称。 Your object is apparently called capital , so you could perhaps do something like this: 您的对象显然称为capital ,因此您可以执行以下操作:

loading <- function(dataset){
   merchants <- load(dataset)
   return(get(merchants))
}

You pass the get() function a string and it returns the object of that name. 您向get()函数传递一个字符串,它返回该名称的对象。

Note that this won't work if there is more than one object saved in the RData file. 请注意,如果RData文件中保存了多个对象,则此方法将无效。 Checking for the presence of more than one object, and potentially returning all objects, is left as an exercise for the reader. 读者不妨检查一下是否存在多个对象,并可能返回所有对象。

Use the envir argument of load to control the place where the loaded variables are stored. 使用loadenvir参数控制存储已加载变量的位置。

Save some variables (to make this reproducible): 保存一些变量(以使其可重现):

x <- 1:10
y <- runif(10)
z <- letters
save(x, y, z, file = "test.RData")

Define your loading function. 定义您的加载功能。 This will return an environment containing x , y , and z . 这将返回包含xyz的环境。

loading <- function(rdata_file)
{
  e <- new.env()
  load(rdata_file, envir = e)
  e
}

Usage is as: 用法如下:

data_env <- loading("test.RData")
ls.str(data_env)
## x :  int [1:10] 1 2 3 4 5 6 7 8 9 10
## y :  num [1:10] 0.6843 0.6922 0.3194 0.0588 0.0146 ...
## z :  chr [1:26] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" ...

Check ls() . 检查ls() You should have variables you saved in "capital.Rdata" loaded. 您应该已加载保存在"capital.Rdata"变量。 Your function returns the variable name you saved, which in this case should be capital . 您的函数返回您保存的变量名称,在这种情况下,该名称应为capital

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

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