我可以通过定义 2 个自定义函数、move_pkg_env
移动package:*
环境和move_env
(使用move_pkg_env
)移动搜索路径中的任何环境来解决它,只要package:*
它的位置和目标之间只有环境:
以下是如何使用它:
something <- list()
attach(something)
library(tidyverse,pos = 3)
search()
# [1] ".GlobalEnv" "package:forcats" "package:stringr"
# [4] "package:dplyr" "package:purrr" "package:readr"
# [7] "package:tidyr" "package:tibble" "package:ggplot2"
# [10] "something" "package:tidyverse" "tools:rstudio"
# [13] "package:stats" "package:graphics" "package:grDevices"
# [16] "package:utils" "package:datasets" "package:methods"
# [19] "Autoloads" "package:base"
move_env("something", 2)
search()
# [1] ".GlobalEnv" "something" "package:forcats"
# [4] "package:stringr" "package:dplyr" "package:purrr"
# [7] "package:readr" "package:tidyr" "package:tibble"
# [10] "package:ggplot2" "package:tidyverse" "tools:rstudio"
# [13] "package:stats" "package:graphics" "package:grDevices"
# [16] "package:utils" "package:datasets" "package:methods"
# [19] "Autoloads" "package:base"
功能:
move_pkg_env <- function(env, at, after = FALSE){
if(is.numeric(env)) env <- search()[env]
if(!startsWith(env, "package:"))
stop("env must be a 'package::*' environment")
if(!env %in% search())
stop(paste(env,"is not on the search path"))
pkg <- sub('package:','',env)
pos <- which(env == search())[1]
if(is.character(at)){
at = which(at == search())[1]
if(is.na(at)) stop(paste(pkg,"is not on the search path"))
}
detach(env,character.only = TRUE)
at <- at + after - (pos < at)
suppressWarnings(library(pkg,pos=at,
warn.conflicts = FALSE,
quietly = TRUE,
character.only = TRUE,
verbose = FALSE))
}
move_env <- function(env, at, after = FALSE){
if(is.numeric(env)) env <- search()[env]
if(!env %in% search())
stop(paste(env,"is not on the search path"))
if(is.character(at)){
at = which(at == search())[1]
if(is.na(at)) stop(paste(pkg,"is not on the search path"))
}
at <- at + after
pos <- which(env == search())[1]
while(pos > at){
move_pkg_env(pos-1,pos+1)
pos <- which(env == search())[1]
}
while(pos < at){
move_pkg_env(pos+1,pos-1)
pos <- which(env == search())[1]
}
}
相关的github问题
https://github.com/tidyverse/tidyverse/issues/159