1

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?

1
  • Without your data I cannot confirm, but using a toy example this works fine for me. Commented May 21, 2013 at 21:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

There has been mention of plans (In the NEWS for version 1.8.2) to add ..() syntax so that .() and ..() are analogous to the file system's ./ and ../; i.e., .() evaluates within the frame of DT and ..() in the parent scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.