【问题标题】:looping between two vectors for meeting three conditions在两个向量之间循环以满足三个条件
【发布时间】:2014-07-08 19:58:48
【问题描述】:

我有一个包含 4 列数据的 csv 文件。我需要从我喜欢的 csv 文件中选择第一列:

file1<-read.csv("file1.csv",header=TRUE)
x<-file[,1]

第一列包含 (x, here) 包含行号。

x
5
10
54
177
178
182
183
184
185
203
204
205
206
207
208

现在有另一个 csv 文件,其中包含 365 行数据的单列

y<-read.csv("data.csv",header=TRUE)

y
0
2.3
0.5
21
0
.
.
.
9.5 #total 365 numbers

这是我打算做的:

1) 从 x 中选择第一个数字(即 5)

2) 在y中选择对应的第5个数据点(即0)和它之前的4个数据点(即21,0.5,2.3,0),然后分别测试以下条件

条件1:从5个数据点中,如果5个中有3个>0,则打印5(步骤1的结果)

条件2:如果五个中的四个都>0,则再次打印5

条件3:如果五个都>0,则再次打印5

但是,如果三个条件中只有前两个满足,第三个不满足,则从x中选择第二个数(本例为10),再次选择y中对应的第10个数据点和四个数据在它之前的点(第 6、7、8 和 9)并评估它们的第三个条件(即如果所有五个数字 - 第 6、7、8、9 和 10 号都 > 0,我不需要评估第一个和x) 中的前一个数字已经满足的第二个条件,然后保存 10 并停止。

这对于我的弱智(从我的声誉来看)来说听起来很复杂,并希望有人能告诉我如何在 R 中做到这一点。

非常感谢

【问题讨论】:

    标签: r function loops


    【解决方案1】:

    听起来你需要一个while循环。

    file1 <- data.frame(x=seq(5, 205, by=5))
    file1
    x <- file1[, 1]
    
    set.seed(123)
    file2 <- data.frame(y=rnorm(365))
    y <- file2[, 1]
    
    # flags for each condition
    cond1 <- FALSE
    cond2 <- FALSE
    cond3 <- FALSE
    
    k <- 0
    while(!cond3) {  
      k <- k + 1
    
      # select first number
      num <- x[k]
    
      # select all y's up to data point
      all.y <- y[(num-4):num]
    
      # number of positive values
      chk.pos <- length(which(all.y > 0))
    
      # condition 1: check if 3 of 5 are positive
      cnt <- 0
      if (!cond1 & chk.pos >= 3) {
        cnt <- cnt + 1
        cond1 <- TRUE
        print(num)
      }
    
      # condition 2:  check if 4 of 5 are positive
      if (!cond2 & chk.pos >= 4) {
        cnt <- cnt + 1
        cond2 <- TRUE
        print(num)
      }
    
      # condition 3:  check if 5 of 5 are positive
      if (!cond3 & chk.pos == 5) {
        cnt <- cnt + 1
        cond3 <- TRUE
        print(num)
      }
    
    }
    

    为我归来

    [1] 5
    [1] 15
    [1] 70
    

    【讨论】:

      猜你喜欢
      • 2017-03-04
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2019-03-30
      • 2014-05-12
      • 1970-01-01
      相关资源
      最近更新 更多