我正在尝试在dplyr summarise. 我正在处理的数据集可以在这里下载并准备使用以下代码:
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")))
Run Code Online (Sandbox Code Playgroud)
这里是 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
Run Code Online (Sandbox Code Playgroud)
对于因子的每个级别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)
Run Code Online (Sandbox Code Playgroud)
但是,我更愿意使用,dpylr因为还有进一步的数据处理要完成,这将是最容易使用summarise输出的。
当我尝试使用该dplyr方法时
test_data %>%
group_by(Chamber) %>%
summarise(cumulative_emmission = last(cumtrapz(Time_cumulative, Flux_N2O)))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Error: Unsupported vector type language
Run Code Online (Sandbox Code Playgroud)
我还尝试cums_ems_func在汇总调用中使用用户定义的函数,结果出现错误:
test_data %>%
group_by(Chamber) %>%
summarise(cumulative_emmission = cum_ems_func())
Error: argument "x" is missing, with no default
Run Code Online (Sandbox Code Playgroud)
任何人都可以指出我正确的方向吗?
如果我理解正确,那么以下之一应该可以完成这项工作
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |