开发者

pack two columns of a matrix in R

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开发者_如何学C 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.


You can do that with lists.

> matrix(apply(B,1,list))
     [,1]  
[1,] List,1
[2,] List,1
[3,] List,1
[4,] List,1
[5,] List,1

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 and signal in a 2n matrix. You may want to write a more elaborate function (e.g. one that identifies the macd and signal columns with their respective instruments).

If you want the macd and signal columns in separate matrices, you could just grep the columns from the out object.

library(quantmod)
getSymbols("SPY;IWM;QQQ")
Data <- Cl(merge(SPY,IWM,QQQ))
out <- do.call(merge, lapply(1:NCOL(Data), function(i) MACD(Data[,i])))


If I understand your question correctly, then:

A[,1] = paste(B[,1], B[,2])

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:

  1. A list (see Joshua's answer)
  2. An array

but we need more details to give you a proper answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜