R中的列表理解

Nic*_*ick 39 r

有没有办法在R中实现列表理解?

像python:

sum([x for x in range(1000) if x % 3== 0 or x % 5== 0])
Run Code Online (Sandbox Code Playgroud)

在Haskell中也一样:

sum [x| x<-[1..1000-1], x`mod` 3 ==0 || x `mod` 5 ==0 ]
Run Code Online (Sandbox Code Playgroud)

在R中应用它的实用方法是什么?

缺口

Mad*_*one 34

像这样的东西?

l <- 1:1000
sum(l[l %% 3 == 0 | l %% 5 == 0])
Run Code Online (Sandbox Code Playgroud)

  • 并不是说会有所作为,但这会更快,因为它使用整数并且不会创建另一个向量:`sum(l*(l %% 3L == 0L | l %% 5L == 0L))` (4认同)
  • @flodel你是对的,我应该严格使用整数.但是在你的解决方案中,如何创建另一个向量?`l %% 3L == 0L | l %% 5L == 0L`不能创建逻辑向量? (4认同)

Nis*_*nth 9

是的,列表理解可以在R中:

sum((1:1000)[(1:1000 %% 3) == 0 | (1:1000 %% 5) == 0])
Run Code Online (Sandbox Code Playgroud)


G. *_*eck 5

这是很多年后的事了,但 CRAN 上现在有三个列表理解包。每个语法都略有不同。所有这些都运行良好,但 listcompr 支持方便的自定义列命名(此处不需要),而 eList 支持与并行包结合的并行处理(此处未显示)。按字母顺序排列:

library(comprehenr)
sum(to_vec(for(x in 1:1000) if (x %% 3 == 0 | x %% 5 == 0) x))
## [1] 234168

library(eList)
Sum(for(x in 1:1000) if (x %% 3 == 0 | x %% 5 == 0) x else 0)
## [1] 234168

library(listcompr)
sum(gen.vector(x, x = 1:1000, x %% 3 == 0 | x %% 5 == 0))
## [1] 234168
Run Code Online (Sandbox Code Playgroud)

另外以下内容仅在 github 上。

# devtools::install.github("mailund/lc")
library(lc)
sum(unlist(lc(x, x = seq(1000), x %% 3 == 0 | x %% 5 == 0)))
## [1] 234168
Run Code Online (Sandbox Code Playgroud)