【问题标题】:calculate percentage change between first and last row of each column in a matrix计算矩阵中每一列的第一行和最后一行之间的百分比变化
【发布时间】:2015-02-21 09:35:12
【问题描述】:

我想找到一种方法来计算下面矩阵中每一列的第一行和最后一行的百分比变化。我尝试过使用 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

【问题讨论】:

  • (df[nrow(df),] - df[1,]) / df[1,]

标签: r loops for-loop percentage


【解决方案1】:

试试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

【讨论】:

  • 谢谢你们 - 在我安装最新版本的 Rstudio 之后,我也刚刚发现了 matrix.head 和 matrix.tail。自动完成功能要好得多,弹出窗口向我展示了这两个我不知道存在的命令。
猜你喜欢
  • 2021-11-19
  • 2021-12-09
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2015-06-24
相关资源
最近更新 更多