I often use loops in my code. I was told that rather than using loops, I should be using functions, and that a loop can be re-written using a function in the R package purr.
As an example the code shows just the counts of the different species in the iris dataset where the 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
}
The loop populates the sepaltable dataframe with the name of each species and how many of them there were in the iris dataset. I want to reproduce the effects of this loop using a function in the R package purrr without using a loop. Can anyone help?