[R] enty-wise closest element

Charles C. Berry cberry at tajo.ucsd.edu
Sun Jan 17 21:39:55 CET 2010


On Sun, 17 Jan 2010, Andreas Wittmann wrote:

> Thank you very much for your quick answers.
>
> Sorry, but i forgot to explain i want to find the closest and smaller element 
> for each entry, so ind1[3] is smaller as 11 and close to 11, ind1[2] is 
> smaller as 5 and close to 5 and ind1[1] is smaller than 3 and close to 3.
>


Perhaps this?

> ind2[ 1 + findInterval(ind1,ind2) ]
[1]  3  5 11
>

If so, be sure to read

 	?findInterval


HTH,

Chuck


> best regards
>
> Andreas
>
>
>
>
>>
>>  On Jan 17, 2010, at 11:00 AM, Andreas Wittmann wrote:
>> 
>> >  Dear R-users,
>> > 
>> >  i have a simple problem maybe, but i don't see the solution. i want to 
>> >  find the entry-wise closest element of an vector compared with another.
>> > 
>> >  ind1<-c(1,4,10)
>> >  ind2<-c(3,5,11)
>> > 
>> >  for (i in length(ind2):1)
>> >  {
>> >  print(which.min(abs(ind1-ind2[i])))
>>> }
>> > 
>> >  for ind2[3] it should be ind1[3] 10, for ind2[2] it should be ind1[2] 4 
>> >  and for ind2[1] it should be ind1[1] 1. but with the for-loop above i 
>> >  get ind1[3], ind1[2] and ind1[2].
>> > 
>> >  any suggestions are quite welcome.
>>
>>  You are failing to use the indices that which.min is providing. (And I
>>  think the closest in ind1 to ind2[1] is not 1, but rather 4, so see if
>>  this looks more responsive to your expectations:
>> 
>> >  for (i in length(ind2):1)
>>  + {
>>  + print( ind1[which.min(abs(ind1-ind2[i]))] )
>>  + }
>>  [1] 10
>>  [1] 4
>>  [1] 4
>> > 
>> >  best regards
>> > 
>> >  Andreas
>> > 
>> >  ______________________________________________
>> >  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.
>>
>>  David Winsemius, MD
>>  Heritage Laboratories
>>  West Hartford, CT
>> 
>
> ______________________________________________
> 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.
>
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list