Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

Vectorize a loop where iterations are dependent on previous ones in R

I have the following working code:

x <- c(10.7, 13.0, 11.4, 11.5, 12.5, 14.1, 14.8, 14.1, 12.6, 16.0, 11.7, 10.6,
       10.0, 11.4, 7.9, 9.5, 8.0, 11.8, 10.5, 11.2, 9.2, 10.1, 10.4, 10.5)

cusum <- function(x) {
  
  s <- NA
  mn <- mean(x)
  
  for (i in seq_along(x)) {
  if (i == 1)
    s[i] <- 0 + x[i] - mn
  else
    s[i] <- s[i - 1] + x[i] - mn
  }
  
  s
  
}

cusum(x)

I wish to vectorize my code for performance, but I do not know how because:

  • I can not use an "iterative dependency" (i.e. s[i - 1] to compute s[i]) in lapply and al.
  • I can not loop over two vectors in Reduce (i.e. s and x)

How can I vectorize my function in base R? I work in a restrictive environment where I only have access to base R.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You don't need loops for this particular iteration: just use cumsum on x - mean(x):

cumsum(x - mean(x))
 [1] -6.958333e-01  9.083333e-01  9.125000e-01  1.016667e+00  2.120833e+00  4.825000e+00  8.229167e+00  1.093333e+01  1.213750e+01
[10]  1.674167e+01  1.704583e+01  1.625000e+01  1.485417e+01  1.485833e+01  1.136250e+01  9.466667e+00  6.070833e+00  6.475000e+00
[19]  5.579167e+00  5.383333e+00  3.187500e+00  1.891667e+00  8.958333e-01 -1.598721e-14

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...