1

我怎样才能创建一个向量S

S[i] = 1, if Tv[i]是最接近整数的数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 ....)

最终目标是有一个像尺子一样的列表,1其中的值最接近下一个整数值。

4

3 回答 3

4

这是一种方法:

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
于 2012-11-25T16:18:21.533 回答
3

这不需要你给I,而只是查找最接近最接近整数的值:

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
于 2012-11-25T16:30:28.540 回答
1

一条线解决方案

diff(floor(c(T[1],T)))
于 2012-11-25T16:34:45.483 回答