【问题标题】:How to write this code in a shorter way with apply or purrr:map?如何使用 apply 或 purrr:map 以更短的方式编写此代码?
【发布时间】:2021-12-07 16:26:41
【问题描述】:

我正在寻找一种解决方案来以更短的方式编写我的代码(如下)(它的工作原理是这样的)。

我创建了一个名为 calculs_geo () 的函数,我正在使用它与不同的参数。

也许使用 apply() 或 purrr::map() ?

提前非常感谢!

calculs_geo(maille = "France",filiere = "ensemble", champ = "ensemble")
calculs_geo(maille = "FrancedeProvince",filiere = "ensemble", champ = "ensemble")
calculs_geo(maille = "REG",filiere = "ensemble", champ = "ensemble")
calculs_geo(maille = "DEP",filiere = "ensemble", champ = "ensemble")
calculs_geo(maille = "ZE2020",filiere = "ensemble", champ = "ensemble")

calculs_geo(maille = "France",filiere="logistique", champ = "ensemble")
calculs_geo(maille = "FrancedeProvince",filiere="logistique", champ = "ensemble")
calculs_geo(maille = "REG",filiere="logistique", champ = "ensemble")
calculs_geo(maille = "DEP",filiere="logistique", champ = "ensemble")
calculs_geo(maille = "ZE2020",filiere="logistique", champ = "ensemble")

calculs_geo(maille = "France",filiere="logistique",champ="6_domaines")
calculs_geo(maille = "FrancedeProvince",filiere="logistique",champ="6_domaines")
calculs_geo(maille = "REG",filiere="logistique",champ="6_domaines")
calculs_geo(maille = "DEP",filiere="logistique",champ="6_domaines")
calculs_geo(maille = "ZE2020",filiere="logistique",champ="6_domaines")

【问题讨论】:

  • 我们需要有关您的数据的更多信息:tidyverse.org/help,了解更多有关 calculus_geo 函数的信息并就适当的输出提供建议也无妨。乍一看,map_2 似乎是您需要的功能,但如果没有其他信息很难说。
  • 是的,对不起,我没有做 reprex,因为我的代码是这样工作的,最终函数包含什么并不重要

标签: r purrr


【解决方案1】:

我们可以创建3个变量名向量并使用purrr::pmap

mailles<-rep(c("France", "FrancedeProvince", "REG", "DEP", "ZE2020"), times = 3)
filieres<-rep(c("ensemble", "logistique", 'logistique'), each = 5)
champs<-rep(c('ensemble', 'ensemble', "6_domaines"), each = 5)

purrr::pmap(list(mailles, filieres, champs), function(x,y,z) caluculs_geo(x, y, z))

这可以简化成purrr::pmap(list(mailles, filieres, champs), caluculus_geo),不看calculus_geo的定义就很难分辨

示例:

calculs_geo<-function(x, y, z) paste(x, y, z, sep = ' + ')

purrr::pmap(list(mailles, filieres, champs), calculs_geo)

[[1]]
[1] "France + ensemble + ensemble"

[[2]]
[1] "FrancedeProvince + ensemble + ensemble"

[[3]]
[1] "REG + ensemble + ensemble"

[[4]]
[1] "DEP + ensemble + ensemble"

[[5]]
[1] "ZE2020 + ensemble + ensemble"

[[6]]
[1] "France + logistique + ensemble"

[[7]]
[1] "FrancedeProvince + logistique + ensemble"

[[8]]
[1] "REG + logistique + ensemble"

[[9]]
[1] "DEP + logistique + ensemble"

[[10]]
[1] "ZE2020 + logistique + ensemble"

[[11]]
[1] "France + logistique + 6_domaines"

[[12]]
[1] "FrancedeProvince + logistique + 6_domaines"

[[13]]
[1] "REG + logistique + 6_domaines"

[[14]]
[1] "DEP + logistique + 6_domaines"

[[15]]
[1] "ZE2020 + logistique + 6_domaines"

【讨论】:

    猜你喜欢
    • 2011-11-19
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多