在 R 中打包矩阵的两列
假设我有一个两列矩阵。如何将列打包成一对/元组,以便将它们分配给单列矩阵?
> A = matrix(NA,nrow=5,ncol=1)
> B = matrix(runif(10),ncol=2)
> A
[,1]
[1,] NA
[2,] NA
[3,] NA
[4,] NA
[5,] NA
> B
[,1] [,2]
[1,] 0.1886287 0.6995596
[2,] 0.1576875 0.9792369
[3,] 0.9056386 0.1640904
[4,] 0.9125812 0.7003167
[5,] 0.9327778 0.8149431
> A[,1] = B # need this to work
我有一个 n 列价格矩阵,每只股票有一列。我正在尝试计算每只股票的移动 MACD 统计数据。我使用 n 列 MACD 矩阵来包含结果。当我将一列价格提供给 MACD 函数(来自 TTR 包)时,它返回信号和 MACD 的 2 列矩阵,因此我需要在同一维度内包含此统计数据。
Suppose I have a two column matrix. How do I pack the columns into a pair/tuple so that they can be assigned to a one column matrix?
> A = matrix(NA,nrow=5,ncol=1)
> B = matrix(runif(10),ncol=2)
> A
[,1]
[1,] NA
[2,] NA
[3,] NA
[4,] NA
[5,] NA
> B
[,1] [,2]
[1,] 0.1886287 0.6995596
[2,] 0.1576875 0.9792369
[3,] 0.9056386 0.1640904
[4,] 0.9125812 0.7003167
[5,] 0.9327778 0.8149431
> A[,1] = B # need this to work
I have a n-col matrix of prices, a column for each stock. I am trying to compute a moving MACD statistic for each stock. I am using a n-col MACD matrix to contain the results. When I feed a one col of prices to MACD function (from package TTR), it returns a 2-col matrix of signal and macd, so I need to way to contain this statistic within the same dimension.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用列表来做到这一点。
也就是说,这是一种非常不符合 R 的做事方式,并且可能带来的麻烦大于其价值。如果您描述了您实际想要做的事情,有人可以向您展示更合适的方法。
更新:
根据更新的问题,下面的代码会将
macd
和signal
放入 2n 矩阵中。您可能想要编写一个更复杂的函数(例如,识别macd
和signal
列及其各自工具的函数)。如果您希望将
macd
和signal
列放在单独的矩阵中,您只需grep
来自out
对象的列即可。You can do that with lists.
That said, this is a very un-R-like way to do things and is probably more trouble than it's worth. If you describe what you're actually trying to do, someone could show you a more appropriate approach.
UPDATE:
Based on the updated question, the code below will put the
macd
andsignal
in a 2n matrix. You may want to write a more elaborate function (e.g. one that identifies themacd
andsignal
columns with their respective instruments).If you want the
macd
andsignal
columns in separate matrices, you could justgrep
the columns from theout
object.如果我正确理解你的问题,那么:
但是,
A
的元素是字符,而不是向量。在矩阵中,每个元素必须是单个值。所以这几乎肯定不是您想要的。还有其他两个选项:
但我们需要更多详细信息才能为您提供正确的答案。
If I understand your question correctly, then:
However, the elements of
A
are characters, not vectors. In a matrix, each element must be a single value. So this is almost certainly not what you want.There are two other options:
but we need more details to give you a proper answer.