I have some code which passes a list containing some strings to another function. Thing is the new function doesn't use the string associated with the index, but rather uses the index number.
How do I force it to use the string value behind the index value?
My code
for (i in 1:length(cList)) {
cList[i] <- GetData(cList[i], StartMonth, StartNumberofMonth, StartYear, EndMonth, EndNumberofMonth, EndYear)
}
GetData <- function (TickerID, StartMonth, StartNumberofMonth, StartYear, EndMonth, EndNumberofMonth, EndYear) {
url1 <- "http://real-chart.finance.yahoo.com/table.csv?s="
url2 <- paste0(TickerID, "&a=", StartMonth-1, "&b=")
url3 <- paste0(StartNumberofMonth, "&c=", StartYear)
url4 <- paste0("&d=", EndMonth -1, "&e=", EndNumberofMonth)
url5 <- paste0("&f=", EndYear, "&g=d&ignore=.csv")
#/ Generate CSV URL link
url.final <- paste(url1, url2, url3, url4, url5)
}
When I write print (url.final
) I get
[1] "http://real-chart.finance.yahoo.com/table.csv?s= 4&a=1&b= 1&c=2013 &d=1&e=1 &f=2015&g=d&ignore=.csv"
TickerID List
[1] BABA
Levels: ABBV ABEV ACT BABA KMI LFC MA ORCL TSM UPS
As you can see, the index value has been used, not the string behind it. I already tried casting TickerID
with as.character
, with the same result (not working).
The error is cList
is a list, so you cannot cast directly to character the component you get with cList[i]
, because this is also a list!
If you have myList = list(a=1, b=2, c=3)
, myList[1]
and myList[1:2
] are lists (try class(myList[1])
and class(myList[1:2])
to check). On the other hand, myList[[1]]
provides you with the content of the first element of the list, which is numeric (try class(myList[[1]])
).
To keep your approach, you can unlist your list (with just one element) using this:
cList[i] <- GetData(as.character(unlist(cList[i])), StartMonth, StartNumberofMonth, StartYear, EndMonth, EndNumberofMonth, EndYear)
or index directly the contents of the i-th element of the list using the doble brace:
cList[i] <- GetData(as.character(cList[[i]]), StartMonth, StartNumberofMonth, StartYear, EndMonth, EndNumberofMonth, EndYear)