简体   繁体   English

R:将一个矩阵的值映射到另一矩阵的阶上

[英]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). “ order”是一个矩阵,其中包含我想要数据的顺序(其中1是事件,零是非事件)。 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. 但是,我这里不需要1或0,我想要一个值,A或B或其他任何值。

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. 因此,A和B替换了1。 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. 因此,如果第i行以AAB ...开头的值,并且第i行的顺序为100101,则结果应为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. 几个小时以来,我一直在用for循环弄乱,以使其在R中起作用,这真让我发疯。 I strongly suspect there is a non-for loop option here, but I honestly don't care how I get the end result. 我强烈怀疑这里有一个非for循环选项,但老实说我不在乎如何获得最终结果。 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")]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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