【发布时间】:2019-11-07 17:36:17
【问题描述】:
我经常在我的代码中使用循环。有人告诉我,我应该使用函数,而不是使用循环,并且可以使用 R 包 purr 中的函数重写循环。
作为示例,代码仅显示了鸢尾花数据集中不同物种的计数,其中 Sepal.Width
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
}
循环使用每个物种的名称以及鸢尾花数据集中有多少物种来填充可分离的数据框。我想在不使用循环的情况下使用 R 包 purrr 中的函数来重现此循环的效果。有人可以帮忙吗?
【问题讨论】: