Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Return a data frame to the workspace, and name it from a function argument

Tags:

function

r

I want to create a data frame within a function and return it to the workspace, but additionally to be able to name that data frame each time I call that function (by passing a text string as function argument). Below is my best guess but doesn't do it.

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

func("my.data.frame")
like image 522
BDA Avatar asked Dec 04 '25 10:12

BDA


1 Answers

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

But anyway, you need to specify the environment where you want to assign the new data.frame. Right now you are defaulting to the function environment 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")
like image 183
MrFlick Avatar answered Dec 07 '25 06:12

MrFlick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!