R data.table 使用列作为参数将函数应用于行 [英] R data.table apply function to rows using columns as arguments
本文介绍了R 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"))
我想对 data.table
的每一行应用一个函数.func.test
函数使用参数 f1
和 f2
并对其进行处理并返回一个计算值.假设(例如)
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)
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?
推荐答案
最好的办法是写一个向量化的函数,但如果你不能,那么也许这样做:
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 = seq_len(nrow(x))]
这篇关于R data.table 使用列作为参数将函数应用于行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文