计算矩阵中每一列的第一行和最后一行之间的百分比变化

calculate percentage change between first and last row of each column in a matrix

我想找到一种方法来计算下面矩阵中每一列的第一行和最后一行的百分比变化。我试过使用 for 循环和 tail(df[i],1)/head(df[i],1) -1 但我似乎做对了。

为这个愚蠢的问题道歉,但我在这里感到非常沮丧..

 df=matrix(c(3,9,3,4,3,9,3,5,3,8,8,8),4,3)
 df
 ### return list/vector of 3 elements where values are 4/3 -1, 5/3 -1, and 8/3 -1 ....the returns of the last over first

试试 apply:

> df <- matrix(c(3,9,3,4,3,9,3,5,3,8,8,8),4,3)
> df
     [,1] [,2] [,3]
[1,]    3    3    3
[2,]    9    9    8
[3,]    3    3    8
[4,]    4    5    8
> apply(df, 2, function(col) (col[nrow(df)]/col[1]) - 1)
[1] 0.3333333 0.6666667 1.6666667