dplyr中summarise函数的R用户自定义函数

6
我正在尝试在 dplyrsummarise 中使用用户定义的函数。 我正在处理的数据集可以从这里下载,并可使用以下代码进行准备:
raw_data <- read.csv("Output/FluxN2O.csv", stringsAsFactors = FALSE)
test_data <- raw_data %>% mutate(Chamber = as.factor(Chamber), Treatment = as.factor(Treatment. Time = as.POSIXct(Time, format = "%Y-%m-%d %H:%M:%S")))

这是 head()
> head(test_data)
             Time Chamber_closed         Slope R_Squared Chamber Treatment   Flux_N2O Time_relative Time_cumulative
1 2016-05-03 00:08:21          10.23  8.873843e-07 0.6941540      10        AN  0.7567335           0.0             0.0
2 2016-05-03 06:10:21          12.24 -5.540907e-06 0.7728001      12         U -4.7251117         362.0           362.0
3 2016-05-03 06:42:21          10.24 -5.260463e-06 0.9583473      10        AN -4.4859581          32.0           394.0
4 2016-05-03 07:12:21           9.23 -5.320429e-06 0.7602987       9        IU -4.5370951          30.0           424.0
5 2016-05-03 07:42:21           7.23  3.135043e-06 0.7012436       7         U  2.6734669          30.0           454.0
6 2016-05-03 20:10:15           5.24  5.215290e-06 0.7508935       5        AN  4.4474364         747.9          1201.9

对于因子“Chamber”的每个水平,我想计算当x =“Time_cumulative”和y =“Flux_n2O”时曲线下的面积。
我可以使用以下函数通过“by”调用来实现:
cum_ems_func <- function(x) {last(cumtrapz(x$Time_cumulative, x$Flux_N2O))}
by(test_data, test_data$Chamber, cum_ems_func)

然而,我更倾向于使用 dplyr,因为还有进一步的数据处理需要进行,而使用 summarise 输出最容易实现。
当我尝试使用 dplyr 方法时...
test_data %>% 
group_by(Chamber) %>% 
summarise(cumulative_emmission = last(cumtrapz(Time_cumulative, Flux_N2O)))

我遇到了以下错误:
Error: Unsupported vector type language

我还尝试在summarise调用中使用用户定义的函数,但结果出现错误:
test_data %>% 
group_by(Chamber) %>% 
summarise(cumulative_emmission = cum_ems_func())
Error: argument "x" is missing, with no default

“请问有人可以指点我正确的方向吗?”

请在您的问题中添加 dput(head(test_data)) - Pierre L
最后一种方法需要您向函数传递一些数据,但是根据您定义的方式,它将需要整个数据框架的数据组,该数据框架由“.”表示。如果您愿意,可以重新定义函数以接受两个变量,这样您就可以只传递列名。前一个版本更常见,并且据我所知应该可以工作。什么是“cumtrapz”函数及其参数? - alistaire
@alistaire cumtrapz 是一个用梯形积分法计算曲线下面积的函数。它是“pracma”包的一部分。我尝试使用 .,但它给了我每个 Chamber 因子水平相同的值。我将尝试更改该函数。 - Rory Shaw
1个回答

0

如果我理解正确,那么以下其中一个应该可以完成工作

library(pracma); library(dplyr)


test_data <- test_data %>% group_by(Chamber) %>% 
             mutate(emission=max(cumtrapz(Time_cumulative, Flux_N2O))) %>% ungroup

### or 

test_data <- test_data %>% group_by(Chamber) %>% 
             mutate(cumulative_emission=cumtrapz(Time_cumulative, Flux_N2O)) %>% ungroup

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接