Skip to content
Prev 6356 / 12125 Next

[R-pkg-devel] Assigning a variable to global environment

Thanks, everyone,

Following Mark suggestion:

The problem I'm trying to solve is:
Users of my package metan (https://CRAN.R-project.org/package=metan),
sometimes need to extract 2-3 variables from a given data.frame and put
them as vectors in the global environment to use in other package's
functions.
Given that df has the columns, ENV, GEN, REP, I would need to run the
following codes
ENV <- df$ENV
GEN <- df$GEN
REP <- df$GEN
I'm looking for a more efficient way to do that and just finished the
following function

as_vector <- function(.data, ...){
  if(missing(...)){
    df <- select(.data, everything())
  } else{
    df <- select(.data, ...)
  }
  for(i in 1:ncol(df)){
    var_name <- names(df[i])
    var_name <- ifelse(exists(var_name, envir = .GlobalEnv),
                         paste(var_name, "_vct", sep = ""),
                         var_name)
    assign(var_name, as.vector(df[[i]]), envir = .GlobalEnv)
  }
}

Then, users could simply run as_vector(df) or  as_vector(df, GEN, ENV)
But I'm not sure if this fits with the CRAN policies.
Cherss,
Tiago

Em sex., 11 de dez. de 2020 ?s 16:03, Ben Bolker <bbolker at gmail.com>
escreveu: