将选定的变量输出到全局环境 R 函数

Output selected variables to global environment R function

我有一个功能,它是这里先前问题的扩展

下面是我的函数

library(outliers)
MscoreMax <- 3

scores_na <- function(x, ...) {
  not_na <- !is.na(x)
  scores <- rep(NA, length(x))
  scores[not_na] <- outliers::scores(na.omit(x), ...)
  scores
}


mediansFunction <- function(x){
  labmedians <- sapply(x[-1], median)
  median_of_median <- median(labmedians)
  grand_median <- median(as.matrix(x[-1]))
  labMscore <- as.vector(round(abs(scores_na(labmedians, "mad")), digits = 2)) #calculate mscore by lab
  labMscoreIndex <- which(labMscore > MscoreMax) #get the position in the vector that exceeds Mscoremax
  x[-1][labMscoreIndex] <- NA # discharge values above threshold by making NA
  
     
       return(x) 
}


该函数具有将高于阈值的我的 Mscore 值转换为 NA 的预期结果。但是,我想发送

从函数内部作为全局环境的自身变量,而不是作为 3 个变量的项目列表。我可以这样做还是更好地创建第二个稍微不同的函数,将变量作为函数发送到全局环境,然后在函数外部使用 list2env 将变量提取为单独的项目?

下面是我的df

structure(list(Determination_No = 1:6, `2` = c(0.08, 0.08, 0.08, 
0.08, 0.08, 0.08), `3` = c(0.08, 0.07, 0.07, 0.08, 0.07, 0.07
), `4` = c(0.07, 0.08, 0.08, 0.08, 0.07, 0.08), `5` = c(0.08, 
0.08, 0.08, 0.08, 0.09, 0.09), `7` = c(0.09, 0.09, 0.11, 0.1, 
0.1, 0.1), `8` = c(0.086, 0.087, 0.086, 0.09, 0.083, 0.079), 
    `10` = c(0.049748274, 0.049748274, 0.066331032, 0.066331032, 
    0.066331032, 0.049748274), `12` = c(0.086, 0.078, 0.078, 
    0.077, 0.077, 0.068)), class = "data.frame", row.names = c(NA, 
-6L))


不建议从函数内部写入全局环境。如果要在全局环境中创建多个对象 return 函数中的命名列表并使用 list2env.

mediansFunction <- function(x){
  labmedians <- sapply(x[-1], median)
  median_of_median <- median(labmedians)
  grand_median <- median(as.matrix(x[-1]))
  labMscore <- as.vector(round(abs(scores_na(labmedians, "mad")), digits = 2)) #calculate mscore by lab
  labMscoreIndex <- which(labMscore > MscoreMax) #get the position in the vector that exceeds Mscoremax
  x[-1][labMscoreIndex] <- NA # discharge values above threshold by making NA
  dplyr::lst(data = x, labmedians, grand_median, labMscore)
}

result <- mediansFunction(df)
list2env(result, .GlobalEnv)

现在全局环境中有变量 datalabmediansgrand_medianlabMscore