R beginner: matrix algebra
diff(x) will returns the diff's of each column when x is a matrix, so there is no need for the apply call. E.g.,
d <- ts(cbind(SQRE=(1:7)^2, CUBE=(1:7)^3), start=2012.25, deltat=1/4) d
SQRE CUBE 2012 Q2 1 1 2012 Q3 4 8 2012 Q4 9 27 2013 Q1 16 64 2013 Q2 25 125 2013 Q3 36 216 2013 Q4 49 343
diff(d)
SQRE CUBE 2012 Q3 3 7 2012 Q4 5 19 2013 Q1 7 37 2013 Q2 9 61 2013 Q3 11 91 2013 Q4 13 127 filter() will do it also and may be more convenient because its output is the same length as its input:
filter(d, c(1,-1), sides=1)
[,1] [,2] 2012 Q2 NA NA 2012 Q3 3 7 2012 Q4 5 19 2013 Q1 7 37 2013 Q2 9 61 2013 Q3 11 91 2013 Q4 13 127 Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com
-----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Richard M. Heiberger Sent: Monday, December 17, 2012 1:54 PM To: kevj1980 Cc: r-help at r-project.org Subject: Re: [R] R beginner: matrix algebra I think this is what you are looking for.
tmp <- matrix(sample(20), 5, 4) tmp
[,1] [,2] [,3] [,4] [1,] 6 15 18 20 [2,] 4 5 10 19 [3,] 7 9 1 3 [4,] 8 14 11 13 [5,] 17 12 16 2
t(apply(tmp, 1, diff))
[,1] [,2] [,3] [1,] 9 3 2 [2,] 1 5 9 [3,] 2 -8 2 [4,] 6 -3 2 [5,] -5 4 -14
On Mon, Dec 17, 2012 at 12:16 PM, kevj1980 <kevin.kidney at cameronhume.com>wrote:
Hi, I have an n x m matrix of numerical observations. ie. stock prices I wish to convert the matrix of observations to a matrix of simple returns (by taking the differences between (column) observations.) Can any good soul suggest a function for this? -- View this message in context: http://r.789695.n4.nabble.com/R-beginner-matrix-algebra-tp4653335.html Sent from the R help mailing list archive at Nabble.com.
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
______________________________________________ R-help at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.