我想在R中做一些相对简单的事情;我正在尝试计算矩阵的每个组件从一行到下一行的百分比变化。这是我正在运行的代码
> fun <- function(x) diff(x, lag=1)/lag(x,1);
> mat <- dx[2490:2520,];
> mat <- apply(mat, 2, fun);
There were 30 warnings (use warnings() to see them)
> warnings()
Warning messages:
1: In diff(x, lag = 1)/lag(x, 1) :
longer object length is not a multiple of shorter object length
R控制台将此消息返回给我,我不明白为什么。如果这不起作用,有人可以指出另一种计算百分比变化的方法吗?对此有任何帮助表示赞赏。
答案 0 :(得分:0)
如果输入为m
行和n
列,并且您希望输出为m-1
行和n
列,则:
(mat <- matrix(sample(50, 15, replace = TRUE), nr=3, nc=5))
## [,1] [,2] [,3] [,4] [,5]
## [1,] 28 2 21 9 2
## [2,] 18 11 8 2 24
## [3,] 21 2 20 8 21
apply(mat, 2, function(cc) (cc[-1] - head(cc, n = -1)) / head(cc, n = -1))
## [,1] [,2] [,3] [,4] [,5]
## [1,] -0.3571429 4.5000000 -0.6190476 -0.7777778 11.000
## [2,] 0.1666667 -0.8181818 1.5000000 3.0000000 -0.125
或者,甚至更快:
nr <- nrow(mat)
(mat[-1,] - mat[-nr,]) / mat[-nr,]
## [,1] [,2] [,3] [,4] [,5]
## [1,] -0.3571429 4.5000000 -0.6190476 -0.7777778 11.000
## [2,] 0.1666667 -0.8181818 1.5000000 3.0000000 -0.125