R data.table使用列作为参数将函数应用于行 [英] R data.table apply function to rows using columns as arguments

查看:151
本文介绍了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 使用args 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?

推荐答案

最好的办法是写一个矢量化函数,但如果你不能, p>

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

这篇关于R data.table使用列作为参数将函数应用于行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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