I have a two column matrix, m
. I have a vector of Booleans index
, generated based on the sequence within m[,1]
. I would like to replace some values in m[,2]
, with values from m[,1]
but only where the same row in index
is TRUE
.
我有一个两列矩阵,m。我有一个布尔值索引,基于m [,1]内的序列生成。我想用m [,2]中的一些值替换m [,1]中的值,但仅限于索引中的同一行为TRUE的值。
I'm sure there is an good way to do this without looping, but I can't get my head around it at the moment. I have tried many ways but failed. Here is my code:
我确信有一个很好的方法可以在没有循环的情况下做到这一点,但我现在无法理解它。我尝试了很多方法但失败了。这是我的代码:
m <- matrix(nrow=20,ncol=2)
m[,2] <- 0
m[,1] <- c(0, 0, 0, 1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, 1, 1)
index <- (m[,1]==Lag(m[,1])) & (m[,1]!=Lag(m[,1],2))
I would appreciate any insight on an elegant way to achieve the correct result.
我希望能够以优雅的方式获得正确的结果。
Thank you.
谢谢。
1 个解决方案
#1
1
This should work:
这应该工作:
m[which(index),2] <- m[which(index),1]
gives you
给你
> m
[,1] [,2]
[1,] 0 0
[2,] 0 0
[3,] 0 0
[4,] 1 0
[5,] 1 1
[6,] 1 0
[7,] -1 0
[8,] 1 0
[9,] 1 1
[10,] 1 0
[11,] 1 0
[12,] -1 0
[13,] -1 -1
[14,] -1 0
[15,] -1 0
[16,] -1 0
[17,] 1 0
[18,] 1 1
[19,] 1 0
[20,] 1 0
Note that m[index,2]
etc. would also work if there were no NA
values in index
.
请注意,如果索引中没有NA值,m [index,2]等也会起作用。
#1
1
This should work:
这应该工作:
m[which(index),2] <- m[which(index),1]
gives you
给你
> m
[,1] [,2]
[1,] 0 0
[2,] 0 0
[3,] 0 0
[4,] 1 0
[5,] 1 1
[6,] 1 0
[7,] -1 0
[8,] 1 0
[9,] 1 1
[10,] 1 0
[11,] 1 0
[12,] -1 0
[13,] -1 -1
[14,] -1 0
[15,] -1 0
[16,] -1 0
[17,] 1 0
[18,] 1 1
[19,] 1 0
[20,] 1 0
Note that m[index,2]
etc. would also work if there were no NA
values in index
.
请注意,如果索引中没有NA值,m [index,2]等也会起作用。