在R中查找行索引

时间:2015-05-03 07:21:29

标签: r

我有一个M乘N的实数矩阵R.条目R [m,n]给出月m和模拟n的股价收益。我想找到最早的月份,在所有模拟中都会出现负面回报。

我可以为每列找到第一次出现负回报,然后找到最小值。但是有更有效的方法吗?

问题在R 中执行此操作的最有效方法是什么?

1 个答案:

答案 0 :(得分:2)

可能有更快的方法,但这里有一个解决方案:

set.seed(3)
dat <- matrix(
  runif(n = 120, -5, 100), 
  nrow = 12,
  dimnames = list(paste0("month", 1:12), paste0("simulation", 1:10)))

head(dat, n = 7)

# simulation1 simulation2 simulation3 simulation4 simulation5 simulation6 simulation7 simulation8 simulation9 simulation10
# month1   12.644360   51.073712    19.87293    88.40622    27.97330   80.691136    89.84239   95.309603    29.05762     3.301263
# month2   79.789222   53.511191    78.07048    16.20436    79.06731    1.049364    96.45969   83.054696    27.15497    27.818028
# month3   35.418947   86.131546    57.97181    55.81453    19.07909   79.297071    49.10195   17.409618    14.34961    29.132973
# month4   29.412103   82.119413    90.56551    16.80136    17.36484    5.960723    52.69547   46.944923    66.39763     3.228478
# month5   58.220571    6.702161    53.84458    24.55422    87.09560   75.493632    12.19059   61.805647    75.46546    10.773076
# month6   58.461376   68.887278    74.34900    77.55953    99.28831   27.005109    12.28268   91.714596    66.62388    11.004632
# month7    8.086512   89.236268    34.81305    13.16703    83.64594   75.775179    77.56494   -3.766876    16.95873    90.909478

which(apply(dat, MARGIN = 1, FUN = function(currentRow) {
  any(currentRow < 0)
}))[1]