views:

158

answers:

2

I am interested in (functional) vector manipulation in R. Specifically, what are R's equivalents to Perl's map and grep?

The following Perl script greps the even array elements and multiplies them by 2:

@a1=(1..8); 
@a2 = map {$_ * 2} grep {$_ % 2 == 0} @a1;
print join(" ", @a2)
# 4 8 12 16

How can I do that in R? I got this far, using sapply for Perl's map:

> a1 <- c(1:8)
> sapply(a1, function(x){x * 2})
[1]  2  4  6  8 10 12 14 16

Where can I read more about such functional array manipulations in R?

Also, is there a Perl to R phrase book, similar to the Perl Python Phrasebook?

+6  A: 

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.

amarillion
+8  A: 

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"

Dirk Eddelbuettel