我想删除当前环境中的所有对象,除了其中两个,就像这样
rm(list=setdiff(ls(),c("current_object_a","current_object_b")))
Run Code Online (Sandbox Code Playgroud)
但是我想在一个函数中调用它.如果我现在这样做,没有任何反应,因为我正在删除函数内的环境变量,而不是全局环境.
你必须指定环境都ls和rm.
rm(list = setdiff(ls(globalenv()),
c("current_object_a", "current_object_b")),
pos = globalenv())
Run Code Online (Sandbox Code Playgroud)
但是,真的,你为什么要这样做?从函数中删除全局环境中的东西似乎是一件坏事.
您可以使用posor envir参数指定环境
rm(list=setdiff(ls(pos=globalenv()),
c("current_object_a","current_object_b")),
pos=globalenv())
Run Code Online (Sandbox Code Playgroud)
从 ?rm
'pos'参数可以用以下几种方式指定从中移除对象的环境:作为整数('search'列表中的位置); 作为搜索列表中元素的字符串名称; 或者作为'环境'(包括使用'sys.frame'来访问当前活动的函数调用).'envir'参数是指定环境的另一种方法,但主要用于反向兼容.