R: how to avoid explicit names when using a variable

I have the following code in R:

library(quantmod)

mySymbol = "^STOXX50E"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(STOXX50E))

      

which simply load the time series for the inder Eurostoxx and then plot the closing price. It works as expected. Anyway, I was wondering how I can avoid writing "STOXX50E" explicitly every time I want to refer to this variable. For example, I would like to be able to refer to a variable containing data with a common name such as "INDEX" so that I do not need to change all the calls when I want to run the code with a different inder.

For example, if I want to download and plot the closing price for the S & P500, I must do:

library(quantmod)

mySymbol = "^GSPC"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(GSPC))

      

so I need to change the variable name not only on the second line but also on the last one. I would prefer something more general:

library(quantmod)

mySymbol = "^GSPC"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(mySymbol))

      

So, once I have set a name for mySymbol, I don't need to change all the rest of the code. But it doesn't work. How can i do this?

+3


source to share


2 answers


You can do it like this:

library(quantmod)

mySymbol = "^STOXX50E"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(get(substring(mySymbol,2,nchar(mysymbol)))))

      

If you want to change the title of the graph, follow these steps:

chartSeries(Cl(get(substring(mySymbol,2,nchar(mysymbol)))), name=mySymbol)

      

Essentially, when you use getSymbols

, the named variable STOXX50E

is stored in your global environment that contains the data. Using get

, you can access the variable name by specifying a string, ie "^ STOXX50E". Then I use substring

to escape the first character of the mySymbol variable which ^

.

And it works. You are essentially changing mySymbol

and the code works without having to change anything else!



enter image description here

EDIT:

This is probably the best way in that the code is more readable and you avoid the annoying ^

header:

library(quantmod)

mySymbol = "STOXX50E"
getSymbols(paste('^',mySymbol,sep=''), from="2004-01-01", to=Sys.Date())

chartSeries(Cl(get(mySymbol)),name=mySymbol)

      

enter image description here

+1


source


An alternative to the currently accepted solution is to use auto.assign=FALSE

when called getSymbols

.

library(quantmod)
mySymbol <- "^STOXX50E"
x <- getSymbols(mySymbol, from="2004-01-01", to=Sys.Date(), auto.assign=FALSE)
chartSeries(Cl(x), name=mySymbol)
# If you want to remove the "^" from the name:
chartSeries(Cl(x), name=sub("^","",mySymbol,fixed=TRUE))

      



I prefer this solution because I find the code clearer and easier to understand.

+2


source







All Articles