我正在尝试在 dplyr
中使用用户定义的函数summarise
.
我正在处理的数据集可以是 downloaded here并准备使用以下代码:
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)
但是,我更愿意使用
dpylr
因为还有进一步的数据处理要完成,使用 summarise
最容易。输出。当我尝试使用
dplyr
方法test_data %>%
group_by(Chamber) %>%
summarise(cumulative_emmission = last(cumtrapz(Time_cumulative, Flux_N2O)))
我收到以下错误:
Error: Unsupported vector type language
我也尝试过使用用户定义的函数
cums_ems_func
在带有结果错误的汇总调用中:test_data %>%
group_by(Chamber) %>%
summarise(cumulative_emmission = cum_ems_func())
Error: argument "x" is missing, with no default
任何人都可以指出我正确的方向吗?
最佳答案
如果我理解正确,那么以下之一应该可以完成这项工作
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
关于dplyr中的R用户定义函数总结,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596308/