首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R数据编程中的For和If

R数据编程中的For和If
EN

Stack Overflow用户
提问于 2021-01-01 14:00:53
回答 1查看 64关注 0票数 0

我想评估非零数据之间的距离。所以如果我有50个数据,并且只有第一个和最后一个数据是非零的,那么我想要的结果是49。

例如,我的数据是:

代码语言:javascript
复制
1. 0
2. 0
3. 5
4. 6
5. 0
6. 1
7. 0

根据我上面的数据,我想得到4个变量:

代码语言:javascript
复制
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)

这是我的密码:

代码语言:javascript
复制
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

结果是:

代码语言:javascript
复制
[1]  1 NA NA NA  1  1

你能帮我解决这个问题吗?我还希望代码使用某种循环,以便可以应用于任何其他数据。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-01 14:23:10

问题中的一般规则并不明确,但是如果x是输入,我们假设:

输入是non-negative

  • the,输出中的第一个元素是第一个+v元素在x

  • subsequent中的位置,输出元素是x

  • if的连续+ve元素之间的距离,其结果是一个向量,其和小于length(x),并附加了余数

为了确定c(1, x)的正元素的位置,使用diff计算该约简向量中连续元素之间的差异,如果它们不和length(x),则追加余数。

代码语言:javascript
复制
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

在这里,它使用一个循环重做:

代码语言:javascript
复制
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

更新

根据以下答复的评论进行简化。加环法。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65530299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档