R将函数应用于两个向量的连续值

时间:2018-07-05 09:22:09

标签: r vector apply

我正在尝试将函数应用于两个向量的连续值。问题可以简化为:

x = c(2,4,6,8,10)
y = c(1,2,3,4,5)

for (i in 1:(length(x)-1)) {
    a = mean(x[i:(i+1)])
    b = mean(y[i:(i+1)])
    print(a/b)
}

我想知道通过使用apply系列中的函数来做一个更有效的方法是什么?谢谢!

4 个答案:

答案 0 :(得分:4)

Name                     Value    item
buying fish hook         240      fish hook
arrange lunch            75       lunch
repair equipment         800      equipment
purchase air condition   1400     air condition

答案 1 :(得分:4)

您可以使用基数R:

a = sapply(1:(length(x)-1),function(x)x:(x+1))
colMeans(structure(x[a],.Dim=dim(a)))/colMeans(structure(y[a],.Dim=dim(a)))
[1] 2 2 2 2

甚至

 tapply(x[a], col(a), mean)/tapply(y[a], col(a), mean)

这些基本功能似乎比rollapply更快地工作,因为rollapply将两次执行rollapply:

microbenchmark::microbenchmark(
   COLMEANS={a=sapply(1:(length(x)-1),function(x)x:(x+1))
   colMeans(structure(x[a],.Dim=dim(a)))/
     colMeans(structure(y[a],.Dim=dim(a)))},
   ROLLAPPLY=rollapply(x,2,mean)/rollapply(y,2,mean),
   TAPPLY={a=sapply(1:(length(x)-1),function(x)x:(x+1))
     tapply(x[a], col(a), mean)/tapply(y[a], col(a), mean)
   },
   ROLLMEANS=rollmean(x,2) / rollmean(y,2)
 )
 Unit: microseconds
      expr      min        lq      mean   median        uq      max neval
  COLMEANS   76.517  109.0040  187.7223  138.499  178.0405 4598.685   100
 ROLLAPPLY 1752.185 1954.8040 2144.2619 2028.543 2211.9260 6244.430   100
    TAPPLY  398.827  519.3725  665.5016  604.224  682.4505 5304.859   100
ROLLMEANS 1366.610 1619.6715 1815.3349 1731.0260 1957.7965 2615.240   100

答案 2 :(得分:3)

您可以使用Zoo库中的rollapply:

  library(zoo)
  rollapply(x,2,mean)/rollapply(y,2,mean)

答案 3 :(得分:3)

好吧,也许是显而易见的,但是:

(x[-1] + x[-length(x)]) / (y[-1] + y[-length(x)])
# [1] 2 2 2 2

(比Onyambu基准的COLMEANS解决方案快15倍)