简体   繁体   English

data.table 在 R 中按行应用函数

[英]data.table applying function by row in R

I have a function that takes arguments and I want to apply it over each row in a data.table.我有一个带参数的函数,我想将它应用于 data.table 中的每一行。

My data looks like follows:我的数据如下所示:

Row    Temp   Humidity  Elevation
1       10      0.5       1000
2       25      1.5       2000
3       28      2.0       1500

and I have a function我有一个功能

myfunc <- function(x, n_features=3){
# Here x represents each row of a data table.
# Feature names are important for me as my actual function is operating on feature names

return(x[,Temp]+x[,Humidity]+(x[,Elevation]*(n_features)))

}

What I want my output to look like is我希望我的输出看起来像

Row    Temp   Humidity  Elevation   myfuncout
1       10      0.5       1000      3010.5
2       25      1.5       2000      6026.5
3       28      2.0       1500      4530

I have tried df[, myfuncout := myfunc(x, n_features=3), by=.I] but this didnt work.我试过df[, myfuncout := myfunc(x, n_features=3), by=.I]但这没有用。 Also, not sure if I have to use .SD here to make this work... Any inputs here on how I can achieve this?另外,不确定我是否必须在这里使用.SD来完成这项工作......这里有关于我如何实现这一目标的任何输入? Thanks!谢谢!

If it is a data.table , we can use如果是data.table ,我们可以使用

myfunc <- function(dt,  n_features = 3) {  
     dt[, out := (Temp + Humidity) + (Elevation * n_features)]  
     dt
}         

myfunc(df, 3)

-output -输出

df
#   Row Temp Humidity Elevation    out
#1:   1   10      0.5      1000 3010.5
#2:   2   25      1.5      2000 6026.5
#3:   3   28      2.0      1500 4530.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM