What are R's equivalents to Perl's map and grep?

Quick ones:

  • Besides sapply, there are also lapply(), tapply, by, aggregate and more in the base. Then there are loads of add-on package on CRAN such as plyr.

  • For basic functional programming as in other languages: Reduce(), Map(), Filter(), ... all of which are on the same help page; try help(Reduce) to get started.

  • As noted in the earlier answer, vectorisation is even more appropriate here.

  • As for grep, R actually has three regexp engines built-in, including a Perl-based version from libpcre.

  • You seem to be missing a few things from R that are there. I'd suggest a good recent book on R and the S language; my recommendation would be Chambers (2008) "Software for Data Analysis"


R has "grep", but it works entirely different than what you're used to. R has something much better built in: it has the ability to create array slices with a boolean expression:

a1 <- c(1:8)
a2 <- a1 [a1 %% 2 == 0]
a2
[1] 2 4 6 8

For map, you can apply a function as you did above, but it's much simpler to just write:

a2 * 2
[1]  4  8 12 16

Or in one step:

a1[a1 %% 2 == 0] * 2
[1]  4  8 12 16

I have never heard of a Perl to R phrase book, if you ever find one let me know! In general, R has less documentation than either perl or python, because it's such a niche language.