SiKiHe
SiKiHe

Reputation: 449

Can I make a function in R return a named object?

I want to write a function that creates a time series, but I'd like it to generate the name of the time series as part of the call.

Sort of

makeTS(my.data.frame, string(dateName), string(varName)){
-create time series tsAux from my.data.frame, dateName and varName
-create string tsName
(-the creation of tsAux is not a problem)
assign(tsName, tsAux)
return(tsName)
} 

This, perhaps not surprisingly, returns the string tsName, but is there any way that I can make it return a named object?

I've tried with

do.call('<-', list(tsName, tsAux))

and I've also tried using

as.name(tsName) <- tsAux

but nothing seems to work.

I know that

tsName <- makeTS2(my.data.frame, dateName, varName) 

would do the trick (where makeTS2() just generates the time series tsAux and returns it), but is there any way to make it work with one function call?

Thanks!

Upvotes: 1

Views: 1344

Answers (2)

LauriK
LauriK

Reputation: 1929

Ari B.' answer is good. You could also use assign() with a variable.

> makeTS <- function(dat) {
+   return(666)
+ }
> varName <- "tmp"
> tmp
Error: object 'tmp' not found
> assign(varName, makeTS(1))
> tmp
[1] 666

Upvotes: 1

Ari B. Friedman
Ari B. Friedman

Reputation: 72779

Can you? Sure:

makeTS <- function(dat, varName) {
  result <- NA
  assign( varName, result, envir = .GlobalEnv )
  result
}

> makeTS(NA, "test")
[1] NA
> test
[1] NA

Should you? Almost surely not.

Upvotes: 8

Related Questions