如何使用
创建向量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
标尺的列表,其值最接近下一个整数值。
答案 0 :(得分: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
答案 1 :(得分:2)
这不要求您提供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
答案 2 :(得分:0)
一线解决方案
diff(floor(c(T[1],T)))