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?
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:
For map, you can apply a function as you did above, but it’s much simpler to just write:
Or in one step:
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.