简体   繁体   中英

Add new data.frame column based on values in other columns

I'm trying to iterate over a data table to calculate the integral of two columns, a dt$xmin and a dt$xmax , with a function f , having the answer be written to a new column dt$integral . I'm currently trying to use something like the below code without success:

dt$integral <- mapply(f, dt$xmin, dt$xmax)

Any help would be greatly appreciated!

Perhaps you do not need mapply and a simple assignment should work dt$integral<- f(dt$min, dt$max) . There is no data or example of what you want but here's what I think could work for you (using data.table ):

library(data.table)
dt <- as.data.table(mtcars)
newfunc <- function(a, b){
  return(a + log(b) - exp(a/b) + 3.1*a^1.918)
}

# Adding a new column called "newcol"
> head(dt[, newcol := newfunc(wt, mpg/qsec),])

    mpg cyl disp  hp drat    wt  qsec vs am gear carb    newcol
1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4  14.73145
2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4  16.30387
3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1  11.45233
4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1  13.87593
5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2  13.78816
6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1 -10.84599

For a single new column the above style of variable assignment would work. For multiple new columns and functions, you would need to use a function that returns a list for the new columns. Look up more on assignment using := in data.table .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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