[英]replace a column given the position of a negative number of another vector in R?
A<-matrix(c(1,2,1,1,1,2,1,1,1),nrow=3,ncol=3)
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 1 1
[3,] 1 2 1
B<-c(1,2,-1)
For example I want to replace all of the third column with all NA's because the third element in B is negative.例如,我想用所有 NA 替换所有第三列,因为 B 中的第三个元素是负数。 I was thinking something like this
我在想这样的事情
NegNum<-length(B[B<0])
A[,tail(NegNum)]<-NA
The negative numbers are always in the last n positions of B so i tried to use tail but im not sure how it works.负数总是在 B 的最后 n 个位置,所以我尝试使用 tail 但我不确定它是如何工作的。
I would suggest indexing based on B
:我建议基于
B
建立索引:
#Matrix 1
A<-matrix(c(1,2,1,1,1,2,1,1,1),nrow=3,ncol=3)
#Vector
B<-c(1,2,-1)
#Solution
A[,which(B<0)]<-NA
Output:输出:
[,1] [,2] [,3]
[1,] 1 1 NA
[2,] 2 1 NA
[3,] 1 2 NA
Here is another base R option这是另一个基本的 R 选项
A %*% diag(replace(B, B < 0, NA))
or或者
replace(A,cbind(seq(nrow(A)),rep(which(B<0),nrow(A))),NA)
which gives这使
[,1] [,2] [,3]
[1,] 1 1 NA
[2,] 2 1 NA
[3,] 1 2 NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.