填充矩阵时维度不匹配 [英] Dimension Does Not Match When Populating Matrix

查看:81
本文介绍了填充矩阵时维度不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在R中工作,我正在尝试使用以下方法填充矩阵 一些循环.但是,我不断收到要替换的项目数不是替换长度的倍数"错误.我设置matrix()的方式是我指定了nrow (因为我确定大小),所以我将ncol留为空白.

I am currently working in R and I am trying to populate a matrix with a some for loops. However, I keep getting the "number of items to replace is not a multiple of replacement length" error. The way I set my matrix() is that I specified nrow (because I am sure of the size) and I leave the ncol blank.

如何创建动态分配尺寸的矩阵?

How can I create a matrix that dynamically allocate the dimensions?

有什么建议吗? 谢谢.

Any recommendations? Thank you.

推荐答案

想到了两个选择:

  • 对矩阵的大小做出明智的猜测,并据此进行分配.然后让您的代码检查以查看是否会超出所选限制并展开该对象.如果您以合理的块大小进行扩展(即,不添加一列,而是根据问题的大小添加10或20或 n ,无论合理的大小),那么您就不会招致经常复制/扩展开销,如果写得不好,这就是沼泽循环的原因.

  • Make an informed guess as to the size of the matrix and allocate accordingly. Then have your code check to see if you would exceed the limits chosen and expand the object. If you expand by a reasonable chunk size (i.e. don't add just 1 column, add 10 or 20 or n depending on the size of your problem, whatever is reasonable) then you won't incur the copy/expand overhead that often, which is what bogs loops down if written badly.

将数据/结果存储在一个列表中,该列表的每个组件将是矩阵的一行.这样一来,您就可以随心所欲地填充对象,然后可以将结果列表填充为矩阵,也可以直接使用该列表.如果每一行可以具有不同的长度(列数),那么首先存储为矩阵是没有意义的,列表是更好的选择.

Store the data/result in a list, each component of which would be one row of your matrix. That way you fill in the object as you go along, and then can either process the resulting list into a matrix with padding, or just work directly with the list. If each row can be of a different length (number of columns) then it doesn't make sense to store as a matrix in the first place and the list is the better option.

这篇关于填充矩阵时维度不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆