Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-如何将data.table的环境传递给函数?_R_Function_Data.table - Fatal编程技术网

R-如何将data.table的环境传递给函数?

R-如何将data.table的环境传递给函数?,r,function,data.table,R,Function,Data.table,我想这样做: 例如,我有一个data.table作为: dt <- data.table(a=1:3, b=5:7, c=10:8) # a b c #1: 1 5 10 #2: 2 6 9 #3: 3 7 8 一种方法是调整函数以接收给定的数据。表和一行并输出您的x+y+z: f <- function(dataTable,row_id){ a <- dataTable[row_id,a] b <- dataTable[row_id,b]

我想这样做:

例如,我有一个data.table作为:

dt <- data.table(a=1:3, b=5:7, c=10:8)
#   a b  c
#1: 1 5 10
#2: 2 6  9
#3: 3 7  8

一种方法是调整函数以接收给定的
数据。表
和一行并输出您的
x+y+z

f <- function(dataTable,row_id){
    a <- dataTable[row_id,a]
    b <- dataTable[row_id,b]
    c <- dataTable[row_id,c]

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}

问题是我会手动分配150个变量,我想做一些更简单的事情,比如当程序查找
a
值时,它直接从
dt[row\u id]
环境中获取。@RafaelToledo,看看上面的编辑是否能完成您要查找的内容。它完成了任务,但这仍然不是我想要的。我在函数的开头使用
attach(dt[row\u id])
并在末尾使用
detach(dt[row\u id])
实现了一个更类似于我想要的解决方案。这对我有帮助,但我认为这可以做得更好。
f <- function(row_id){
    # set function parent env as data.table[row_id]
    # and *a = data.table[row_id, a]* and successively to b and c...

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
f <- function(dataTable,row_id){
    a <- dataTable[row_id,a]
    b <- dataTable[row_id,b]
    c <- dataTable[row_id,c]

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}
f <- function(dataTable,row_id){

    for(i in colnames(dataTable)){
        assign(paste(i,"",sep=""), dataTable[row_id,..i])
    }

    x <- a*b
    y <- a*c
    z <- a/b

    return( x + y + z)
}