简体   繁体   English

清洁环境以加速 R 中的功能

[英]Clean environment to speed up function in R

I have this example data and some example functions我有这个示例数据和一些示例函数

other_data<-c(1,2,3) # data I have to have
fun<-function(a,b,c){
data<-c(a,b,c)
return(data)
} # first function

var_1<-runif(20,10,20) # variables
var_2<-runif(20,10,20)
var_3<-runif(20,10,20)

vars<-data.frame(var_1,var_2,var_3) # data frame of variables
subfun<-function(x){
res<-fun(vars[x,1],vars[x,2],vars[x,3])
return(res)
} # sub function of the first one to use more options and get them into list

final<-lapply(c(1:nrow(vars)),subfun) # this should be the final result I want to get

The problem is, that my real data is much more bigger and I have about 500 "data" (like in first function) which has to be reloaded every time because of different values of a,b,c .问题是,我的真实数据要大得多,而且我有大约 500 个“数据”(就像在第一个函数中一样),由于a,b,c值不同,每次都必须重新加载这些数据。 And it seems to slow down the function because of memory, ie environment.而且它似乎因为内存,即环境而减慢了功能。 I don't want to do it like rm(data) and repeat it 500x times in first function before the row return(data) .我不想像rm(data)那样做,并在行return(data)之前在第一个函数中重复 500 次。 So my questions所以我的问题

Is there any straightforward way how to remove all objects which was loaded during the function, but only these objects in fun(a,b,c) ?有没有什么简单的方法可以删除在函数期间加载的所有对象,但只有fun(a,b,c)这些对象? Because I need to DONT remove other_data .因为我需要不要删除other_data

Or more simply, is there straightforward way how to delete all objects like rm(ls(),instead of=c("other_data") ?或者更简单地说,是否有直接的方法来删除所有对象,如rm(ls(),instead of=c("other_data")

If you only want to keep certain object you can use function keep from library gdata.如果您只想保留某些对象,您可以使用库 gdata 中的函数 keep。 http://www.inside-r.org/packages/cran/gdata/docs/keep http://www.inside-r.org/packages/cran/gdata/docs/keep

library('gdata')
var1 <- 1
var2 <- 2

ls()
[1] "var1" "var2"

keep(var1, sure = T)    
ls()
[1] "var1"

Setting sure to True performs the removal.设置确定为 True 执行删除。 Otherwise keep will return names of objects that would have been removed.否则,keep 将返回将被删除的对象的名称。

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

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