我想评估非零数据之间的距离。所以如果我有50个数据,并且只有第一个和最后一个数据是非零的,那么我想要的结果是49。
例如,我的数据是:
1. 0
2. 0
3. 5
4. 6
5. 0
6. 1
7. 0根据我上面的数据,我想得到4个变量:
v0 = 3 (because the distance between 0th to 3rd data is 3 jumps)
v1 = 1 (because the distance between 3rd to 4th data is 1 jump)
v2 = 2 (because the distance between 4rd to 6th data is 2 jump)
v3 = 1 (because the distance between 6rd to 7th data is 1 jump)这是我的密码:
data=c(0,0,5,6,0,1,0)
t=1
for (i in data) {
if (i == 0) {
t[i]=t+1
}
else {
t[i]=1
}
}
t结果是:
[1] 1 NA NA NA 1 1你能帮我解决这个问题吗?我还希望代码使用某种循环,以便可以应用于任何其他数据。
发布于 2021-01-01 14:23:10
问题中的一般规则并不明确,但是如果x是输入,我们假设:
输入是non-negative
x
x
length(x),并附加了余数。
为了确定c(1, x)的正元素的位置,使用diff计算该约简向量中连续元素之间的差异,如果它们不和length(x),则追加余数。
dists <- function(x) {
d <- diff(which(c(1, x) > 0))
if (sum(d) < length(x)) c(d, length(x) - sum(d)) else d
}
# distance to 5 is 3 and then to 6 is 1 and then to 1 is 2 and 1 is left
x1 <- c(0, 0, 5, 6, 0, 1, 0)
dists(x1)
## [1] 3 1 2 1
# distance to first 1 is 1 and from that to second 1 is 3
x2 <- c(1, 0, 0, 1)
dists(x2)
## [1] 1 3在这里,它使用一个循环重做:
dists2 <- function(x) {
pos <- 0
out <- numeric(0)
for(i in seq_along(x)) {
if (x[i]) {
out <- c(out, i - pos)
pos <- i
}
}
if (sum(out) < length(x)) out <- c(out, length(x) - sum(out))
out
}
dists2(x1)
## [1] 3 1 2 1
dists2(x2)
## [1] 1 3更新
根据以下答复的评论进行简化。加环法。
https://stackoverflow.com/questions/65530299
复制相似问题