0

我创建了一个函数'mywsobj',它接受一个输入和两个输出

用户输入:环境

输出1:一个data.frame名称“wsobj”(对象列表的数据,它们的类,它们的内存使用情况)输出到控制台输出2:对象列表的条形图及其内存使用情况。

到目前为止一切正常,

我的问题1:但是如何在用户指定的输入环境中或至少在 .GlobalEnv 中从函数内部保存该“wsobj” data.frame ?我尝试阅读以下内容:<< 的使用、pos/parent.environment 的使用等,但事情远远超出了我的范围。

我的问题2:是否可以在 R/特别是在 Rstudio 服务器中指定项目特定/用户特定环境?

虽然我在这里的代码可能并不重要,但它在下面:

    # creating SOME data
dfAtoZ<- data.frame(LETTERS) 
df1to1Cr <- data.frame(1:10000000)
vec1to1Cr <- as.vector(1:10000000)
mat1to1Cr <- as.matrix(1:10000000)
set.seed<-10
randvec<-runif(1000,min=-100,max=100)
# creating MY function
mywsobj<-function(myenvironmentName)
{#step1 creating vector of object names
wslist <- vector(length=length(ls(myenvironmentName)))
for(i in 1:length(ls(myenvironmentName)))
{wslist[i]<-ls(myenvironmentName)[i]}
# wslist<-cbind(unlist(ls()))
#step2 creating vector of object classes
wsclass <- vector(length=length(wslist))
wsmemKb <- vector(mode="numeric",length=length(wslist))
for(i in 1:length(wslist))
{wsclass[i]<-class(get(wslist[i]))
wsmemKb[i]<- object.size(get(wslist[i]))/1000*1024}
#step4 combining them in a data.frame
wobj<-data.frame(cbind(wslist,wsclass,wsmemKb))
# library(sqldf)
# sqldf("pragma table_info(wobj)") shows col 3(wsmem) still non-numeric
wobj[,3] <- as.numeric( as.character(wobj[,3]) )
# create data to return matrix of memory consumption
objmemsize <- rev(sort(sapply(ls(envir=myenvironmentName), 
                function (object.name)object.size(get(object.name))/1000)))
# draw bar plot
barplot(objmemsize,main="Memory usage by object in myenvironment", 
          ylab="KiloByte", xlab="Variable name", 
            col=heat.colors(length(objmemsize)))
# result <- sqldf("select * from wobj order by 1/wsmemKb")
return(wobj)
#   return(data.frame(myenvironmentName,wobj))
#   return(assign("myname",wobj,envir = .GlobalEnv))
#   attach(wobj,pos=2,"wobj")
return(barplot)
}
# use of mywsobj function
mywsobj(.GlobalEnv)
# saving output of mywsobj function
output<-as.data.frame(mywsobj(.GlobalEnv))   
4

1 回答 1

3

不确定这是否是您所追求的。但是,您可以使用$.

my_fun <- function(in.env) {
    # you may want to check if input argument is an environment

    # do your computations
    set.seed(45)
    x <- sample(10)
    y <- runif(10)
    in.env$val <- sum(x*y)
}

my_fun(my.env <- new.env())
ls(my.env)
[1] "val"
my.env$val
# [1] 22.30493

或者,您也可以assign按如下方式使用:

my_fun <- function(in.env) {
    # you may want to check if input argument is an environment

    # do your computations
    set.seed(45)
    x <- sample(10)
    y <- runif(10)
    assign("val", sum(x*y), envir=in.env)
}

# assign to global environment
my_fun(globalenv())
> val
# [1] 22.30493

# assign to local environment, say, v
v <- new.env()
my_fun(v)
> v$val
# [1] 22.30493
于 2013-03-17T11:11:58.560 回答