1

i have a function that returns averaged timeseries (using package hydroTSM). However, i want not only to output the averages but also to create a variable with specified name ("d2m"+argument name), so i can access those values later. This is what I've come up so far.

d2m = function(var) {
    d2m = daily2monthly(var, FUN = mean)
    assign(paste('d2m', var, sep = ''), d2m)
    }

I was yet not able to create the output variable. For function argument var=123 i should get a variable called d2m123 with the timeseries as a value. Thanks.

Sotos
  • 51,121
  • 6
  • 32
  • 66
  • 2
    Not clear what you mean. Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Jan 22 '18 at 12:27

3 Answers3

0

It is rarely necessary to assign variables like this - I would suggest that you may wish to use some other type of data structure to store the results of your function calls, such as a list (see SO question Why is using assign bad? for a fuller discussion).

To answer what you have asked you are correctly assigning a variable, but it is only in scope within the function. If you read the help on assign (type ? assign in your console) you will see details of the envir argument. You need to specify .GlobalEnv if you want to see the value from wherever you called it:

d2m = ...
  assign(paste('d2m', var, sep = ''), d2m, envir = .GlobalEnv)

but as mentioned I'd suggest that you give more thought to a suitable data structure to store your function call results.

Stewart Ross
  • 1,034
  • 1
  • 8
  • 10
0
d2m <- function(var) {
  d2m <- daily2monthly(var, FUN = mean)
  assign(paste("d2m", var, sep = ""), d2m, envir = globalenv())
}
sgt Fury
  • 170
  • 1
  • 7
0

I works for me using xts object as function argument:

d2m = function(var) {
  d2m = daily2monthly(var, FUN = mean)
  varName<-deparse(substitute(var))
  assign(paste("d2m", varName, sep = ""), d2m, envir = globalenv())
}
Antonios
  • 1,919
  • 1
  • 11
  • 18