如何使用R包purrr中的函数重现循环

Bas*_*sil 3 r purrr

我经常在代码中使用循环。有人告诉我,我应该使用函数,而不是使用循环,并且可以使用R包purr中的函数来重写循环。

例如,代码仅显示了虹膜数据集中Sepal.Width <3的不同物种的计数

 library(dplyr)
 #dataframe to put the output in
 sepaltable <- data.frame(Species=character(),
                     Total=numeric(), 
                     stringsAsFactors=FALSE) 

 #list of species to iterate over
 specieslist<-unique(iris$Species)

 #loop to populate the dataframe with the name of the species 
 #and the count of how many there were in the iris dataset

 for (i in  seq_along (specieslist)){
 a<-paste(specieslist[i])  
 b<- filter(iris,`Species`==a & Sepal.Width <=3)
 c<-nrow(b)
 sepaltable[i,"Species"]<-a
 sepaltable[i,"Total"]<-c
 }
Run Code Online (Sandbox Code Playgroud)

该循环使用每个物种的名称以及虹膜数据集中的物种数量填充可分离的数据框。我想使用R包purrr中的函数来重现此循环的效果,而不使用循环。有人可以帮忙吗?

akr*_*run 5

我们可以sum在逻辑表达式中使用分组依据dplyr

library(dplyr)
iris %>% 
   group_by(Species) %>%
   summarise(Total = sum(Sepal.Width <=3))
Run Code Online (Sandbox Code Playgroud)

或者如果purrr需要

library(purrr)
map_dfr(specieslist,  ~iris %>% 
      summarise(Total = sum(Species == .x & Sepal.Width <=3),
          Species = .x )) %>%
   select(Species, Total)
Run Code Online (Sandbox Code Playgroud)

注意:mapapply系列功能(lapply/sapply/vapply/rapply/mapply/Map/apply)都是循环

  • 同意akrun-没有理由在此处实施purrr。 (3认同)