Jonas Stein
Jonas Stein

Reputation: 7043

Find closest values to a list of integers

How can I create a vector S, with

S[i] = 1, if Tv[i] is the closest number to an integer in I<- 6:10 S[i] = 0 else

Tv <- c(5.946, 5.978, 
6.01, 6.043, 6.075, 6.109, 6.14, 6.173, 6.205, 6.239, 
6.273, 6.309, 6.344, 6.379, 6.415, 6.45, 6.486, 6.521, 6.556, 
6.59, 6.627, 6.665, 6.703, 6.741, 6.778, 6.816, 6.852, 6.891, 
6.928, 6.967, 7.005, 7.045, 7.084, 7.124, 7.161, 7.202, 7.24)

S <- getS(Tv)

> dput(S) 
c(0, 0, 1, 0, 0 ....)

Final goal is to have a list like a ruler with 1 where the value is closest to the next integer value.

Upvotes: 1

Views: 2576

Answers (3)

agstudy
agstudy

Reputation: 121568

One line solution

diff(floor(c(T[1],T)))

Upvotes: 1

Roland
Roland

Reputation: 132696

This doesn't require you to give I, but just looks up values closest to the nearest integer:

test <- c(5.946, 5.978,6.01, 6.043, 6.075, 6.109, 6.14, 6.173, 6.205, 6.239, 6.273, 6.309, 6.344, 6.379, 6.415,
       6.45, 6.486, 6.521, 6.556, 6.59, 6.627, 6.665, 6.703, 6.741, 6.778, 6.816, 6.852, 6.891,
       6.928, 6.967, 7.005, 7.045, 7.084, 7.124, 7.161, 7.202, 7.24)

res <- integer(length(test))
res[abs(test-round(test)) %in% c(by(test,round(test),
                                    FUN=function(test) min(abs(test-round(test)))))] <- 1
#[1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0

Upvotes: 3

Julius Vainora
Julius Vainora

Reputation: 48201

Here is one way:

I <- 6:10
S <- numeric(length(T))
S[sapply(I, function(i) which.min(abs(i - T)))] <- 1
S
[1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1

Upvotes: 4

Related Questions