根据R中的另一个矩阵从矩阵中减去值
我有以下两个矩阵和两个向量:
# Matrix A
lsA <- c(1,1,0,1,1,2,1,0,1,2,1,1,0,0,1,1,0,0,0,1)
A <- matrix(lsA,4,5, byrow = T)
# Matrix B
ls <- c("12","23","11","01","12","13","23","11","01","33","12","32","11","00","12","12","02","22","02","03")
B <- matrix(ls,4,5, byrow = T)
# Vectors of p
p1 <- c(0.128, 0.130, 0.280, 0.500, 0.650)
p2 <- c(0.055, 0.120, 0.250, 0.430, 0.600)
我需要根据 B 的值使用 p1 和 p2 中的值将矩阵 A 的每个值居中:
# Centering
for (i in 1:ncol(A)){
A[which(B == "11")]<- 2 - (2*p1[i]); A[which(B == "00")]<- 0 - (2*p1[i]); A[which(B == "01")]<- 1 - (2*p1[i]); A[which(B == "10")]<- 1 - (2*p1[i])
A[which(B == "22")]<- 0 - (2*p2[i]); A[which(B == "33")]<- 2 - (2*p2[i]); A[which(B == "23")]<- 1 - (2*p2[i]); A[which(B == "32")]<- 1 - (2*p2[i])
A[which(B == "12" | B == "21")]<- (1 - p1[i]) + (0 - p2[i]); A[which(B == "03" | B == "30")]<- (0 - p1[i]) + (1 - p2[i])
A[which(B == "13" | B == "31")]<- (1 - p1[i]) + (1 - p2[i]); A[which(B == "20" | B == "02")]<- (0 - p1[i]) + (0 - p2[i])
}
上面的代码接近我需要的,但我不知道如何根据列选择p(p中的每个值对应A中的一列)
有什么想法吗?
I have the following two matrices and two vectors:
# Matrix A
lsA <- c(1,1,0,1,1,2,1,0,1,2,1,1,0,0,1,1,0,0,0,1)
A <- matrix(lsA,4,5, byrow = T)
# Matrix B
ls <- c("12","23","11","01","12","13","23","11","01","33","12","32","11","00","12","12","02","22","02","03")
B <- matrix(ls,4,5, byrow = T)
# Vectors of p
p1 <- c(0.128, 0.130, 0.280, 0.500, 0.650)
p2 <- c(0.055, 0.120, 0.250, 0.430, 0.600)
I need to center each value of matrix A, using the values in p1 and p2, based on values of B:
# Centering
for (i in 1:ncol(A)){
A[which(B == "11")]<- 2 - (2*p1[i]); A[which(B == "00")]<- 0 - (2*p1[i]); A[which(B == "01")]<- 1 - (2*p1[i]); A[which(B == "10")]<- 1 - (2*p1[i])
A[which(B == "22")]<- 0 - (2*p2[i]); A[which(B == "33")]<- 2 - (2*p2[i]); A[which(B == "23")]<- 1 - (2*p2[i]); A[which(B == "32")]<- 1 - (2*p2[i])
A[which(B == "12" | B == "21")]<- (1 - p1[i]) + (0 - p2[i]); A[which(B == "03" | B == "30")]<- (0 - p1[i]) + (1 - p2[i])
A[which(B == "13" | B == "31")]<- (1 - p1[i]) + (1 - p2[i]); A[which(B == "20" | B == "02")]<- (0 - p1[i]) + (0 - p2[i])
}
The code above is close to what I need, but I don't know how to select the p according to the column (each value in p corresponds to a column in A)
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种方法:
Here is one way to do it: