简体   繁体   中英

R: map values of one matrix onto order of another matrix

I have two matrices. "order" is a matrix with the order I want the data in (where 1's are events and zeroes are non-events). Each row gives the order for each record. However, I don't want 1 or 0 here, I want a value, A or B or whatever.

orders <- structure(c("1", "1", "1", "1", "1", "1", "0", "1", "0", "0", 
"0", "0", "0", "0", "0", "0", "1", "0", "0", "0", "0", "0", "0", 
"1", "1", "1", "0", "0", "0", "0", "0", "1", "0", "0", "0", "1", 
"0", "0", "0", "0", "0", "0", "1", "0", "0", "0", "0", "0"), .Dim = c(6L, 
8L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), c("1", 
"2", "3", "4", "5", "6", "7", "8")))

The "values" matrix represents the values I want mapped onto the above order. So the A's and B's replace the 1's. The zeroes stay put. So if row i starts with AAB...for the values, and the order of row i is 100101, then the result should be A00A0B.

values <- structure(c("A", "B", "A", "B", "A", "B", "A", "B", "0", "0", 
"A", "B", "A", "B", "0", "0", "0", "B", "0", "B", "0", "0", "0", 
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", 
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"), .Dim = c(6L, 
8L))

So the output I'm hoping for looks like this:

desired <- structure(c("A", "B", "A", "B", "A", "B", "0", "B", "0", "0", 
"0", "0", "0", "0", "0", "0", "A", "0", "0", "0", "0", "0", "0", 
"B", "A", "B", "0", "0", "0", "0", "0", "B", "0", "0", "0", "B", 
"0", "0", "0", "0", "0", "0", "A", "0", "0", "0", "0", "0"), .Dim = c(6L, 
8L), .Dimnames = list(c("1", "2", "3", "4", "5", "6"), c("1", 
"2", "3", "4", "5", "6", "7", "8")))

I've been messing around with for loops for hours trying to get this to work in R, and it's driving me nuts. I strongly suspect there is a non-for loop option here, but I honestly don't care how I get the end result. Computer time is not a factor, my data set is only in the hundreds of rows. I should also note that the matrices are the same size. Thank you!

Well I found a simple answer that requires a loop, but that's something at least:

desired <- orders
for (i in 1:nrow(data)){
  desired[i,which(orders[i,]=="1")] <- values[i,which(values[i,]!="0")]}

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