colinfang
colinfang

Reputation: 21737

How to access data.table columns in a function in `j` without pass arguments in?

I would like to build a function that can be used in j of a data table. I hope it doesn't require to a column to be passed in explicitly (I am lazy).

The following doesn't work Error in test(x) : object 'x' not found

test <- function(x=NULL){
    list(z=if (is.null(x)) evalq(x, envir=parent.frame()) else x)
}

a <- data.table(x=1:2, y=1:2)

a[, test(x)] // works well
a[, test()]  // error

If I do a[, test(x)] I get

> a[, test(x)]
   z
1: 1
2: 2

I hope a[, test()] give me same thing.

Upvotes: 0

Views: 303

Answers (1)

eddi
eddi

Reputation: 49448

You can get it to work with something like:

test <- function(x=NULL){
    if (is.null(x)) get('x', parent.frame(3)[,list(x)]) else list(x)
}

but this is a really bad idea as it will break once you introduce a by to your data.table statement. That's because you're not giving data.table a chance to figure out what columns you're going to be using and, since it hasn't gained omnipotence just yet, once you obfuscate the columns you need in a function there isn't much it can do for you.

It might be a better idea to post what your actual problem is (or a closer approximation of it) and maybe you'll get alternative suggestions for a solution.

Upvotes: 2

Related Questions