[R] vectorial search for elements with certain attributes
William Dunlap
wdunlap at tibco.com
Thu May 19 22:24:44 CEST 2011
> -----Original Message-----
> From: r-help-bounces at r-project.org
> [mailto:r-help-bounces at r-project.org] On Behalf Of Dennis Murphy
> Sent: Thursday, May 19, 2011 11:38 AM
> To: infochat at gmx.net
> Cc: r-help at r-project.org
> Subject: Re: [R] vectorial search for elements with certain attributes
>
> Hi:
>
> Here's one possible approach:
>
> A <- c(1,3,7,8,10)
> B <- c(5,8)
> apply(outer(A, B, '-'), 2, function(x) min(which(x >= 0)))
> [1] 3 4
Using findInterval() or as.integer(cut()) would use
quite a bit less memory and time for long vectors.
findInterval would be more direct, but I think it
insists on using ">" instead of ">=" in the above code.cut() lets you
choose.
> as.integer(cut(c(5, 8, 8.01), A, right=TRUE))+1
[1] 3 4 5
> as.integer(cut(c(5, 8, 8.01), A, right=FALSE))+1
[1] 3 5 5
> findInterval(c(5, 8, 8.01), A) + 1
[1] 3 5 5
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
>
> HTH,
> Dennis
>
> On Thu, May 19, 2011 at 2:58 AM, <infochat at gmx.net> wrote:
> > I have 2 vectors A and B. For each element of B I'd like to
> find the index of the next higher or equal element in A. And
> I'd like to store it effectiv. E.g.:
> > A <- c(1,3,7,8,10)
> > B <- c(5,8)
> >
> > result: 3, 4
> >
> > I have a possibility but for long vectors it works not very
> effectiv:
> >
> > ans <- sapply(B, function(x) which.max(A[A < x]) )
> > as.integer(ans + 1)
> >
> > Is there anyone how has a better idea?
> > Thank you for your help,
> > Thomas.
> > --
> >
> > ______________________________________________
> > 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.
>
More information about the R-help
mailing list