R 中的循环及其替代方案
我有一个矩阵 (1051*1051),它的对角线上有 0zero,其他地方的值都大于 0zero。目标是有条件地重新分配矩阵中的某些值。例如,我想要实现的标准是这样的:如果任何元素大于 400,那么该行/列元素将被分配一个 0zero 值。
这就是我现在的代码的设置方式:
dl <- 400 # condition
for( i in 1:dim(DIST)[1] ) {
for( j in 1:dim(DIST)[1] ) {
if( DIST[i,j] > dl ) {
DIS[i,j] <- 0
}
}
}
DIST 是原始矩阵(1051*1051)。
DIS 是 DIST 的副本,需要进行编辑。
我的问题: 还有其他方法可以做到这一点吗?更快的方法?
我读到应该避免 R 中的循环。如果有人有更有效的方法请分享。
谢谢。
I have a matrix (1051*1051) that has 0zeros along its diagonal and values greater than 0zero everywhere else. The goal is to conditionally reassign some values in the matrix. For example, the criteria I would like to implement is this: If any element is greater than, say, 400, then that row/column element will be assigned a 0zero value.
This is how my code is setup as of now:
dl <- 400 # condition
for( i in 1:dim(DIST)[1] ) {
for( j in 1:dim(DIST)[1] ) {
if( DIST[i,j] > dl ) {
DIS[i,j] <- 0
}
}
}
DIST is the original matrix (1051*1051).
DIS is the copy of DIST and to be edited.
My question:
Is there any other way to do this? A faster way?
I have read that loops in R should be avoided. If anyone has a more efficient way please share.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用 [] 赋值:
请参阅
?'['
了解其工作原理。关键是DIST>400
生成长度为length(DIST)
(DIST 中的元素数量)的逻辑向量,如果元素 >400,则为 TRUE否则为 FALSE。然后使用该向量对矩阵进行子集化,并且仅分配选定的元素。Just use [] assignment:
See
?'['
for how this works. The key is thatDIST>400
produces a logical vector of lengthlength(DIST)
(the number of elements in DIST), consisting of TRUE if the element is >400 and FALSE otherwise. That vector is then used to subset the matrix, and only the selected elements get assigned to.尝试
完整示例:
Try
Full example:
下面的示例将矩阵视为向量,并使用 row() 和 col() 函数返回条目的相关行和列大于条件。
首先,创建一些虚拟数据:
接下来,我们使用 row() 和 col() 返回一个矩阵,其中包含矩阵中每个条目的行或列索引。
mr
看起来像这样,例如:现在我们设置条件值,并选择
m
中超出条件的单元格:有了这些超出条件的单元格,我们提取这些单元格的唯一行索引和列索引,
这些是您想要设置为 0 的行和列。
这里我们将此设置为零,首先复制
m2
中的m
进行比较:这是两个矩阵:
Here is an example of doing this treating the matrix as a vector and using the
row()
andcol()
functions to return the relevant rows and columns of the entries that are greater than a condition.First, create some dummy data:
Next we use
row()
andcol()
to return a matrix with the row or col index for each entry in the matrix.mr
looks like this, for example:Now we set out condition value, and select those cells of
m
that exceed the condition:Having these cells that exceed the condition, we extract the unique row and column indexes for these cells
these are the rows and columns you want setting to 0.
Here we do this setting to zero, first copying
m
inm2
for comparison:Here are the two matrices: