R data.table将函数应用于使用列作为参数的行

时间:2021-08-09 20:09:36

I have the following data.table

我有以下data.table

x = structure(list(f1 = 1:3, f2 = 3:5), .Names = c("f1", "f2"), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

I would like to apply a function to each row of the data.table. The function func.test uses args f1 and f2 and does something with it and returns a computed value. Assume (as an example)

我想将一个函数应用于data.table的每一行。函数func.test使用args f1和f2并对其执行某些操作并返回计算值。假设(作为例子)

func.text <- function(arg1,arg2){ return(arg1 + exp(arg2))}

but my real function is more complex and does loops and all, but returns a computed value. What would be the best way to accomplish this?

但我的真实函数更复杂,并且循环和所有,但返回计算值。实现这一目标的最佳方法是什么?

3 个解决方案

#1


32  

The best way is to write a vectorized function, but if you can't, then perhaps this will do:

最好的方法是编写一个矢量化函数,但如果你不能,那么也许这样做:

x[, func.text(f1, f2), by = 1:nrow(x)]

#2


7  

We can define rows with .I function.

我们可以使用.I函数定义行。

dt_iris <- data.table(iris)
dt_iris[, ..I := .I]

## Let's define some function
some_fun <- function(dtX) {
    print('hello')
    return(dtX[, Sepal.Length / Sepal.Width])
}

## by row
dt_iris[, some_fun(.SD), by = ..I] # or simply: dt_iris[, some_fun(.SD), by = .I]

## vectorized calculation
some_fun(dt_iris) 

#3


6  

The most elegant way I've found is with mapply:

我找到的最优雅的方式是与mapply:

x[, value := mapply(func.text, f1, f2)]
x
#    f1 f2    value
# 1:  1  3 21.08554
# 2:  2  4 56.59815
# 3:  3  5 151.4132

#1


32  

The best way is to write a vectorized function, but if you can't, then perhaps this will do:

最好的方法是编写一个矢量化函数,但如果你不能,那么也许这样做:

x[, func.text(f1, f2), by = 1:nrow(x)]

#2


7  

We can define rows with .I function.

我们可以使用.I函数定义行。

dt_iris <- data.table(iris)
dt_iris[, ..I := .I]

## Let's define some function
some_fun <- function(dtX) {
    print('hello')
    return(dtX[, Sepal.Length / Sepal.Width])
}

## by row
dt_iris[, some_fun(.SD), by = ..I] # or simply: dt_iris[, some_fun(.SD), by = .I]

## vectorized calculation
some_fun(dt_iris) 

#3


6  

The most elegant way I've found is with mapply:

我找到的最优雅的方式是与mapply:

x[, value := mapply(func.text, f1, f2)]
x
#    f1 f2    value
# 1:  1  3 21.08554
# 2:  2  4 56.59815
# 3:  3  5 151.4132