Reputation: 22332
I can do a map over a list in R with lapply
:
lapply(1:10,function(y) { if (y %% 2 == 0) {y+42}})
(Which gives me a list between 1 and 10 where every other object is NULL).
Furthermore, I can then remove each of these NULL objects with Filter
:
Filter(function(x) !is.null(x),
lapply(1:10,function(y) { if (y %% 2 == 0) {y+42}}))
(Which gives me a list of even numbers between 1 and 10).
Another example, let's say we want to take a list of strings, and filter out all of the strings that start with "a", and then append "Foo" to the remaining ones. The similar technique could be used:
Filter(function(x) !is.null(x),
lapply(c("foo","abar","baz"),
function(y) { if (grepl("^a",y)) {paste("foo",y)}}))
Is there a better way to do a fold over a list in R.
Upvotes: 2
Views: 1752
Reputation: 887038
You could try
y <- 1:10
as.list(y[y%%2==0]+42)
grep
can also work in a vector
grepl(paste(c(2,4,6), collapse="|"), y)
#[1] FALSE TRUE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
y1 <- letters[1:10]
paste('foo', y1[grepl('^a', y1)])
#[1] "foo a"
Upvotes: 1