根据 if 条件更改向量元素 [英] Changing vector elements according to if condition
本文介绍了根据 if 条件更改向量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 pos 作为数组索引的矩阵,它有 24 行和 2 列.在第一列中,它包含值 1,2,3,4.
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
我试过代码
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
这里 s 返回 s=c(1,1,1,4280236) 但结果应该是 s=c(5,6,6,5)
Here s returns s=c(1,1,1,4280236) but the result should be s=c(5,6,6,5)
推荐答案
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
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
这篇关于根据 if 条件更改向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文