bro*_*oli 26 r mapply 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"))
Run Code Online (Sandbox Code Playgroud)
我想将一个函数应用于每一行data.table.该函数func.test使用args f1并对其f2执行某些操作并返回计算值.假设(作为例子)
func.text <- function(arg1,arg2){ return(arg1 + exp(arg2))}
Run Code Online (Sandbox Code Playgroud)
但我的真实函数更复杂,并且循环和所有,但返回计算值.实现这一目标的最佳方法是什么?
edd*_*ddi 42
最好的方法是编写一个矢量化函数,但如果你不能,那么也许这样做:
x[, func.text(f1, f2), by = seq_len(nrow(x))]
Run Code Online (Sandbox Code Playgroud)
mle*_*gge 15
我找到的最优雅的方式是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
Run Code Online (Sandbox Code Playgroud)
我们可以用.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)
Run Code Online (Sandbox Code Playgroud)