I want to return multiple results from a function on columns of data.frame
and add these new columns to the same data.frame
together with other simple calculation.
For a simplified example, if I want to get both integral value and absolute error of sin
function together with the mid points of integral intervals:
df <- data.frame(Lower = c(1,2,3), Upper = c(2,3,4))
setDT(df)
getIntegral <- function(l, u) {
n <- integrate(sin, mean(l), mean(u))
list(Value=n$value, Error=n$abs.error)
}
df[,
c('Value', 'Error', 'Mid') := {
n <- getIntegral(Lower, Upper)
list(n$Value,
n$Error,
(Lower+Upper)/2)
}]
df
Lower Upper Value Error Mid
1: 1 2 0.5738457 6.370967e-15 1.5
2: 2 3 0.5738457 6.370967e-15 2.5
3: 3 4 0.5738457 6.370967e-15 3.5
I don't quite like my approach because separating names of new columns and the values assigned to them makes it hard for me to read, how can I do this task better? It's part of a long data processing chain so I don't want create temp variable outside, so I would prefer solutions using data.table
or dplyr
alone.