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")
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With