简体   繁体   English

如何在R中使用purrr :: map()

[英]How to use the purrr::map() in R

Recently I got to know that the map function from purrr package is really powerful and tried to find out how to use it in the following case: 最近,我知道purrr包中的map函数确实非常强大,并试图找出在以下情况下如何使用它:

Using iris dataset and using purrr::map function, calculate max , mean , min for all variables Sepal.Length , Sepal.Width , Petal.Length , Petal.Width , respectively for each Species (setosa, versicolor, virginica). 使用虹膜数据集并使用purrr::map函数,分别为每个Species (setosa,versicolor和virginica)分别计算所有变量Sepal.LengthSepal.WidthPetal.LengthPetal.Width maxmeanmin Then put the results into a list having 然后将结果放入具有

  • a character: Species name, and 字符:物种名称,以及
  • four vectors: max , mean , min for Sepal.Length , Sepal.Width , Petal.Length , Petal.Width . 四个向量: Sepal.Length maxmeanminSepal.LengthSepal.WidthPetal.Length Petal.Width

Any suggestions? 有什么建议么? I was using dplyr::mutate , but the result format is not what I want. 我正在使用dplyr::mutate ,但是结果格式不是我想要的。

iris %>%
  group_by(Species) %>%
  summarise(MinSL=min(Sepal.Length),
            MaxSL=max(Sepal.Length),
            MeanSL=mean(Sepal.Length),
            MinPL=min(Petal.Length),
            MaxPL=max(Petal.Length),
            MeanPL=mean(Petal.Length))

It will be also nice see if there is a solution using dpylr to do the task. 看看是否有使用dpylr来完成任务的解决方案也很不错。 Thank you! 谢谢!

You don't need purrr. 您不需要purrr。 Try: 尝试:

iris %>%
  group_by(Species) %>%
  summarise_at(vars(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width),
               c("min", "max", "mean"))

Output 输出量

# A tibble: 3 x 13
  Species    Sepal.Length_min Sepal.Width_min Petal.Length_min Petal.Width_min
  <fct>                 <dbl>           <dbl>            <dbl>           <dbl>
1 setosa                 4.30            2.30             1.00           0.100
2 versicolor             4.90            2.00             3.00           1.00 
3 virginica              4.90            2.20             4.50           1.40 
# ... with 8 more variables: Sepal.Length_max <dbl>, Sepal.Width_max <dbl>,
#   Petal.Length_max <dbl>, Petal.Width_max <dbl>, Sepal.Length_mean <dbl>,
#   Sepal.Width_mean <dbl>, Petal.Length_mean <dbl>, Petal.Width_mean <dbl>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM