[英]replace matrix values in R with rownames another matrix
I have a question about matching two matrices in R to perform a very simple calculation. 我有一个关于在R中匹配两个矩阵以执行非常简单的计算的问题。 I have working code (below), but I feel like there must be a more efficient and 'R-like' way to do it.
我有工作代码(下面),但我觉得必须有一个更高效和'R-like'的方式来做到这一点。 Any clues very welcome.
任何线索都非常受欢迎。
The Problem 问题
I have two matrices with related information. 我有两个相关信息的矩阵。 m1 contains a bunch of references.
m1包含一堆引用。 m2 contains data on those references (zeros or ones).
m2包含那些引用的数据(零或一)。 I want to know which rows of m1 have a '0' in the first column and a '1' in the second column when you look up the data from m2.
我想知道当你从m2中查找数据时,第一列中m1的哪些行为'0'而第二列中的哪一行为'1'。 Here's a toy example:
这是一个玩具示例:
> m1 <- matrix(data = c(51,52,53,51,54,55,56,57), nrow = 4, ncol = 2)
> m1
[,1] [,2]
[1,] 51 54
[2,] 52 55
[3,] 53 56
[4,] 51 57
> m2 <- matrix(data = c(0,0,1,0,0,1,1), nrow = 7, ncol = 1)
> rownames(m2) <- c(51,52,53,54,55,56,57)
> m2
[,1]
51 0
52 0
53 1
54 0
55 0
56 1
57 1
General properties are that I can already guarantee that every entry in m1 has a corresponding row name in m2, and I need to do this many millions of times on much larger matrices, so speed is useful. 一般属性是我可以保证m1中的每个条目都有一个相应的行名称,并且我需要在更大的矩阵上进行数百万次,因此速度很有用。
What I want to do is use m2 to figure out which rows of m1 have a zero in the first column, and a 1 in the second column. 我想要做的是使用m2来确定哪一行m1在第一列中为零,在第二列中为1。 In this case, only the final row of m1 has that property.
在这种情况下,只有m1的最后一行具有该属性。
My Solution 我的解决方案
I have a relatively OK solution to this, which uses apply() and is not too bad: 我有一个相对好的解决方案,它使用apply()并且不是太糟糕:
> is.zero.one <- function(line, m2){
+ start = m2[as.character(line[1]),]
+ end = m2[as.character(line[2]),]
+ if(start==0 && end==1){return(TRUE)}
+ else{return(FALSE)}
+}
> apply(m1, 1, is.zero.one, m2)
[1] FALSE FALSE FALSE TRUE
This works fine. 这很好用。 But it feels clunky.
但它感觉笨重。
My question 我的问题
Does anyone know of a smarter/faster/more natural way to do this? 有谁知道更智能/更快/更自然的方式来做到这一点? I had a look at match() and related functions, but couldn't come up with a solution.
我查看了match()和相关函数,但无法提出解决方案。 Ditto for searching around related questions here.
同样在这里搜索相关问题。 Part of the reason for my question is that I'm not a very good R programmer, so even if this turns out to be a decent solution, I'd be very interested to see how others would solve it.
我的问题的部分原因是我不是一个非常优秀的R程序员,所以即使这是一个不错的解决方案,我也很想知道其他人如何解决它。
Thanks for any help. 谢谢你的帮助。
matrix( m2[ match(m1, rownames(m2) )], ncol=2)
[,1] [,2]
[1,] 0 0
[2,] 0 0
[3,] 1 1
[4,] 0 1
m3 <- matrix(m2[match(m1, rownames(m2) )], ncol=2)
which( m3[,1]==0 & m3[,2]==1 )
#[1] 4
m3[,1]==0 & m3[,2]==1
# [1] FALSE FALSE FALSE TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.