Changing vector elements according to if condition

2019-08-31 09:18发布

问题:

I have pos as matrix of array indices that has 24 rows and 2 columns. In first column it contains the values 1,2,3,4.

$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

I tried the code

ch<-c(5,7,10,5)
C<-150
s<-c(1,1,1,1); s
cost<-sum(ch*s)
repeat
{
for(i in 1:24)
{
  for (j in 1:4)
  {
if (pos[i,1]==j) s[j]<-s[j]+1 else s
  }
  if (cost<C)
  {
    break
  }
}
}
s

Here s returns s=c(1,1,1,4280236) but the result should be s=c(5,6,6,5)

回答1:

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

As a variant one can run through the first column of the matrix pos

for (j in pos[24:1, "row"]) {
  s[j] <- s[j]+1  
  cost <- sum(ch*s)
  if (cost>=C) break
}
s; cost


标签: r vector