小编Bas*_*sil的帖子

如何使用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中的函数来重现此循环的效果,而不使用循环。有人可以帮忙吗?

r purrr

3
推荐指数
1
解决办法
83
查看次数

使用 r box 包一次性加载所有函数

我用的是盒装。在我的项目中,我有一个函数文件夹,其中保存了两个函数:hello.r 和 goodbye.r

我可以使用盒子包加载它们:

box::use(functions/hello)
box::use(functions/goodbye)
Run Code Online (Sandbox Code Playgroud)

问题是我的函数文件夹中可能有数十个 .r 文件(每个函数一个 .r 文件)。

有没有一种方法可以一次性加载所有 .r 文件(同时仍然使用 box 包),而不必多次重复 box::use 函数?

r r-box

3
推荐指数
1
解决办法
163
查看次数

删除列表中奇数长度的元素

我有一个列表,我想删除具有奇数长度的元素:

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是奇数。

有什么建议么?

filtering r list

2
推荐指数
2
解决办法
97
查看次数

标签 统计

r ×3

filtering ×1

list ×1

purrr ×1

r-box ×1