[R] Equivalent of Mathematica's Apply

Juan Pablo Romero Méndez jpablo.romero at gmail.com
Wed Jun 25 01:24:35 CEST 2008


Thanks all!

  JP

On Tue, Jun 24, 2008 at 3:30 PM, Franz Mueter <fmueter at alaska.net> wrote:
> 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.
>
>



More information about the R-help mailing list