如何在`j`中的函数中访问data.table列而不传递参数? [英] How to access data.table columns in a function in `j` without pass arguments in?

查看:120
本文介绍了如何在`j`中的函数中访问data.table列而不传递参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个可以在数据表的 j 中使用的函数。我希望它不需要明确传递的列(我懒惰)。

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).

以下不工作错误test(x):未找到对象'x'

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

如果我做 a [,test(x)] 我得到

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

我希望 a [,test()] 给我同样的东西。

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

推荐答案

您可以使用它来处理:

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

但这是一个很糟糕的主意,因为它会破坏一旦你通过 c $ c>到您的 data.table 语句。这是因为你不给 data.table 一个机会来确定你将要使用哪些列,并且因为它还没有获得全能性,

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.

这篇关于如何在`j`中的函数中访问data.table列而不传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆