Re: [R] Equivalent of Mathematica's Apply

From: Franz Mueter <fmueter_at_alaska.net>
Date: Tue, 24 Jun 2008 12:30:01 -0800

Try

> apply(ind, 1, function(i) x[i[1]:i[2]])

which returns a matrix if all sequences are the same length, a list otherwise

-----Original Message-----
From: r-help-bounces_at_r-project.org [mailto:r-help-bounces_at_r-project.org] On Behalf Of Juan Pablo Romero Méndez
Sent: Tuesday, June 24, 2008 11:51 AM
To: r-help_at_stat.math.ethz.ch
Subject: [R] Equivalent of Mathematica's Apply

Hello,

Is there some equivalent function in R of Mathematica's "Apply"

i.e.

Apply[ f, g[a,b]] ==> f[a,b]

In concret, I have a matrix of indexes:

> ind = cbind(1:5, 1:5+5)

> ind

     [,1] [,2]

[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10


and I'd like to extract sequences 1:6, 2:7, 3:8, ..., 5:10 from a vector x.

What would be the most compact way of achieving this?

I've tried

 sapply(1:5, function(i) x[ind[i,1] : ind[i,2]])

Although

 sapply(1:5, function(i) x[seq(ind[i,])])

would be better (if it worked).

Regards,

  Juan Pablo



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 24 Jun 2008 - 20:51:47 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 24 Jun 2008 - 23:30:59 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive