【发布时间】:2026-01-22 20:05:01
【问题描述】:
我想评估非零数据之间的距离。所以如果我有 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
您能帮我解决这个问题吗?我也希望代码使用某种循环,以便它可以应用于任何其他数据。
【问题讨论】:
-
我不明白为什么 v0 从第 0 跳到第 3?
-
在您的代码中,您使用 i 来设置 t[i] 的值。但我假设您的矢量数据中的所有值(而不是从 1 到矢量数据长度的值。所以这仅表示值 t[0]、t[1]、t[5] 和 t[6]将被分配一个值,其余的将是未定义的(NA)。所以你的代码按预期工作。我不确定你到底想得到什么作为输出,所以我无能为力。
标签: r loops for-loop if-statement