根据if条件改变向量元素

时间:2018-04-24 07:51:12

标签: r vector

我有pos作为数组索引的矩阵,有24行和2列。在第一列中,它包含值1,2,3,4。

word1.innerHTML

我尝试了代码

$position
      row col
 [1,]   4   6
 [2,]   1   6
 [3,]   4   5
 [4,]   2   6
 [5,]   1   5
 [6,]   3   6
 [7,]   4   4
 [8,]   2   5
 [9,]   1   4
[10,]   3   5
[11,]   2   4
[12,]   4   3
[13,]   1   3
[14,]   3   4
[15,]   2   3
[16,]   4   2
[17,]   3   3
[18,]   1   2
[19,]   2   2
[20,]   3   2
[21,]   4   1
[22,]   1   1
[23,]   2   1
[24,]   3   1

这里s返回s = c(1,1,1,4280236),但结果应为s = c(5,6,6,5)

1 个答案:

答案 0 :(得分:0)

pos <- structure(c(4L, 1L, 4L, 2L, 1L, 3L, 4L, 2L, 1L, 3L, 2L, 4L, 1L, 
    3L, 2L, 4L, 3L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 6L, 6L, 5L, 6L, 5L, 
    6L, 4L, 5L, 4L, 5L, 4L, 3L, 3L, 4L, 3L, 2L, 3L, 2L, 2L, 2L, 1L, 
    1L, 1L, 1L), .Dim = c(24L, 2L), .Dimnames = list(NULL, c("row", "col")))
ch <- c(5,7,10,5)
C <- 150
s <- c(1,1,1,1)
for (i in 24:1) {
  # for(j in 1:4)
  # {
  #   if (pos[i,1]==j) s[j] <- s[j]+1  
  # }
  j <- pos[i,1]; s[j] <- s[j]+1
  cost <- sum(ch*s)
  if (cost>=C) break
}
s; cost

作为变体,可以遍历矩阵pos

的第一列
for (j in pos[24:1, "row"]) {
  s[j] <- s[j]+1  
  cost <- sum(ch*s)
  if (cost>=C) break
}
s; cost
相关问题