【问题标题】:R user defined function in dplyr summarisedplyr中的R用户定义函数汇总
【发布时间】:2016-11-30 11:32:59
【问题描述】:

我正在尝试在 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

我还尝试在 summarise 调用中使用用户定义函数 cums_ems_func,但结果错误:

test_data %>% 
group_by(Chamber) %>% 
summarise(cumulative_emmission = cum_ems_func())
Error: argument "x" is missing, with no default

谁能指出我正确的方向?

【问题讨论】:

  • 请在您的问题中添加dput(head(test_data))
  • 最后一种方法需要你向函数传递一些数据,但是你定义它的方式,它需要整个data.frame组,由.表示。如果愿意,您可以重新定义该函数以获取两个变量,这样您就可以只传递列名。以前的版本更常见,据我所知应该可以工作。 cumtrapz 函数是什么,它的参数是什么?
  • @alistaire cumtrapz 是一个通过梯形积分计算曲线下面积的函数。它是“pracma”包的一部分。我曾尝试使用.,但它为Chamber 因子的每个级别提供了相同的值。我将尝试更改功能。

标签: r function dplyr


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-11-04
    • 1970-01-01
    • 2021-05-07
    • 2020-12-27
    • 2021-01-25
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多