Reputation: 1117
I have a data.table called prices that has 3 columns: ticker, date and price. I have run
setkey(prices,ticker,date)
If I do this from the code, it works
prices[list("MSFT",as.Date("2013-01-15")]
returning only the row for MSFT in 2013-01-15 However, if I write this function
getPrice <- function(ticker,date) {
prices[list(ticker,date)]
}
it returns the whole data.table I suspect that it has something to do with scoping in the i parameter, but I can't get it to work. How do I query the data.table if I don't know the parameters in advance?
Upvotes: 1
Views: 158
Reputation: 49448
Your problem is the variable names in your function. Change them to be e.g. x
and y
(so that they are not the same as column names in your data.table
) and everything will work. What you're doing now is constructing a data.table
with all of ticker
and date
columns and then joining that, thus recovering the original data.
Another (more robust) option is to do smth like this in your function:
getPrice <- function(ticker,date) {
tmp = list(ticker, date)
prices[tmp]
}
See FAQs 2.12 and 2.13 for more on this - http://datatable.r-forge.r-project.org/datatable-faq.pdf
Upvotes: 3