问题描述
我想从 data.frame 的列返回多个结果,并将这些新列添加到同一个 data.frame 与其他简单的计算一起。
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.
对于一个简化的例子,如果我想得到整数值和绝对误差 sin 函数以及整数区间的中点:
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
我不太喜欢我的方法,因为分离新列的名称和分配给他们的值使我很难阅读,我如何更好地完成这个任务?它是一个长数据处理链的一部分,所以我不想在外面创建temp变量,所以我更喜欢使用 data.table 或 dplyr 单独。
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.
推荐答案
RHS应该是一个值列表, (如果需要,可循环使用)。
The RHS should be a list of values, and each element of the list gets converted to a column (and recycled if necessary).
您的函数已返回列表(每个长度为1)和 Upper)/ 2 返回3个值的向量(这里)。要返回列表,您可以使用函数 c(),如下所示:
Your function already returns a list (of length 1 each) and (Lower+Upper)/2 returns a vector of 3 values (here). In order to return a list, you can use the function c() as follows:
df[, c('Value', 'Error', 'Mid') := c(getIntegral(Lower, Upper), list((Lower+Upper)/2))] # 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
这利用了 c(list,list)会生成一个连接的列表。
This makes use of the fact that c(list, list) results in a concatenated list.
这篇关于从一个函数计算多个列,并将它们添加到data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!