R: Return the data frame to the stage and name it from the function argument

I want to create a data frame inside a function and return it to the stage, but in addition to be able to call that data frame every time I call this function (passing a text string as an argument to the function). Below is my best guess, but doesn't.

func = function(named.df = "NA"){
  df <- data.frame(c(1,2,3), c('a','b','c'))
  assign(named.df, df)
}

func("my.data.frame")

      

+3


source to share


1 answer


This is a very unusual request, are you sure you really want to create a bunch of different varayables data.frame and not a named list of data.frames? The latter seems to be much more natural for R.

But in any case, you need to specify the environment where you want to assign the new data.frame. You are currently using the function environment by default, so it disappears after the function runs. You probably want to assign in the global environment



func <- function(named.df = "NA") {
  df <- data.frame(c(1,2,3), c('a','b','c'))
  assign(named.df, df, envir=.GlobalEnv)
}

func("my.data.frame")

      

+4


source







All Articles