【问题标题】:How to create a function that calculates multiple statistical functions?如何创建一个计算多个统计函数的函数?
【发布时间】:2022-01-09 02:50:22
【问题描述】:

我想对许多向量进行统计分析,例如corMAEbiassdt.testchisq.test、...创建一个函数,我只提供要分析的数据,并提供一个带有计算的向量。

理想情况下,我想输入 vector1 和 vector2,然后进行计算。

现在我正在执行以下操作,但它很快就会变得不可持续。

  ## R^2
rsq_15_18 <- round(cor(x = study_15_18$potential_15, y = study_15_18$overall_18 ,method = "pearson")^2,4)
rsq_16_19 <- round(cor(x = study_16_19$potential_16, y = study_16_19$overall_19 ,method = "pearson")^2,4)
rsq_17_20 <- round(cor(x = study_17_20$potential_17, y = study_17_20$overall_20 ,method = "pearson")^2,4)
rsq_18_21 <- round(cor(x = study_18_21$potential_18, y = study_18_21$overall_21 ,method = "pearson")^2,4)
rsq_19_22 <- round(cor(x = study_19_22$potential_19, y = study_19_22$overall_22 ,method = "pearson")^2,4)

## MAE
mae_15_18 <- round(mae(study_15_18$overall_18, study_15_18$potential_15),4)
mae_16_19 <- round(mae(study_16_19$overall_19, study_16_19$potential_16),4)
mae_17_20 <- round(mae(study_17_20$overall_20, study_17_20$potential_17),4)
mae_18_21 <- round(mae(study_18_21$overall_21, study_18_21$potential_18),4)
mae_19_22 <- round(mae(study_19_22$overall_22, study_19_22$potential_19),4)
  ## Bias
bias_15_18 <- round(bias(study_15_18$overall_18, study_15_18$potential_15),4)
bias_16_19 <- round(bias(study_16_19$overall_19, study_16_19$potential_16),4)
bias_17_20 <- round(bias(study_17_20$overall_20, study_17_20$potential_17),4)
bias_18_21 <- round(bias(study_18_21$overall_21, study_18_21$potential_18),4)
bias_19_22 <- round(bias(study_19_22$overall_22, study_19_22$potential_19),4)

comparison <- c("15_18", "16_19", "17_20", "18_21", "19_22")
R2 <- c(rsq_15_18, rsq_16_19, rsq_17_20, rsq_18_21, rsq_19_22)
MAE <- c(mae_15_18, mae_16_19, mae_17_20, mae_18_21, mae_19_22)
bias <- c(bias_15_18, bias_16_19, bias_17_20, bias_18_21, bias_19_22)
  
data.frame(comparison, R2, MAE, bias)

谢谢,

【问题讨论】:

  • 首先,请查看purrr::map2()。接下来,将您的学习列入清单。 (任何时候你有很多相似的名字,你应该考虑一个列表结构。)

标签: r function coding-efficiency


【解决方案1】:

因此,您有两个要比较的研究列表。将它们放入列表中:

study_overall <- list(study_15_18$overall_18, ...) # fill in ... as needed
study_potential <- list(study_15_18$potential_15, ...)

现在您可以并行处理这些列表:

library(purrr)
cors <- map2_dbl(study_overall, study_potential, 
                  \(x, y) round(cor(x, y, method = "pearson"))
                )

现在您可以将生成的向量放入数据框中。

【讨论】:

  • 您可以通过从匿名函数返回多个统计信息并使用map2_dfr 将它们绑定在一起来做得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多