我经常在代码中使用循环。有人告诉我,我应该使用函数,而不是使用循环,并且可以使用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中的函数来重现此循环的效果,而不使用循环。有人可以帮忙吗?
我用的是盒装。在我的项目中,我有一个函数文件夹,其中保存了两个函数:hello.r 和 goodbye.r
我可以使用盒子包加载它们:
box::use(functions/hello)
box::use(functions/goodbye)
Run Code Online (Sandbox Code Playgroud)
问题是我的函数文件夹中可能有数十个 .r 文件(每个函数一个 .r 文件)。
有没有一种方法可以一次性加载所有 .r 文件(同时仍然使用 box 包),而不必多次重复 box::use 函数?
我有一个列表,我想删除具有奇数长度的元素:
my_list <- list()
my_list$a <- c(1,2,3,4) #length 4
my_list$b <- c(1,2,3) # length 3
my_list$c <- c(5,6,7,8,6,7) #length 6
Run Code Online (Sandbox Code Playgroud)
所以在上面的例子中,我想删除, my_list$b 因为它的长度是3,而3是奇数。
有什么建议么?