简体   繁体   中英

Subtracting values from matrix based on another matrix in R

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?

Here is one way to do it:

for (i in 1:ncol(A)){
  A[B[,i] == "11"),i]<- 2 - (2*p1[i])
  A[B[,i] == "00"),i]<- 0 - (2*p1[i])
  A[B[,i] == "01"),i]<- 1 - (2*p1[i])
  A[B[,i] == "10"),i]<- 1 - (2*p1[i])
  A[B[,i] == "22"),i]<- 0 - (2*p2[i])
  A[B[,i] == "33"),i]<- 2 - (2*p2[i])
  A[B[,i] == "23"),i]<- 1 - (2*p2[i])
  A[B[,i] == "32"),i]<- 1 - (2*p2[i])
  A[B[,i] == "12" | B[,i] == "21"),i]<- (1 - p1[i]) + (0 - p2[i])
  A[B[,i] == "03" | B[,i] == "30"),i]<- (0 - p1[i]) + (1 - p2[i])
  A[B[,i] == "13" | B[,i] == "31"),i]<- (1 - p1[i]) + (1 - p2[i])
  A[B[,i] == "20" | B[,i] == "02"),i]<- (0 - p1[i]) + (0 - p2[i])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM