更新时间:2022-10-15 15:50:06
可以用循环或应用或向量化来完成它。
> x(1,2,3,4,5)
> r< - NA
>对于(n in 2:length(x))r [n] > (r)
[1] NA 1 1 1 NA
>
> r< - NA
> lapply(2:length(x),function(n)r [n] [1] 1
[[2]]
[1] 1
[[3]]
[1] 1
[[4]]
[1] NA
> (r)
[1]不适用1 1 1不适用
> r< - NA
> (x(x),x(1)),其中x(x,y) (r)
[1] NA 1 1 1 NA
矢量化是最高效的代码难以破译
> x< - runif(50000)
>
> r< - NA
> system.time(for(n in 2:length(x))r [n] 8.55 0.01 8.58
>
> r< - NA
> system.time(lapply(2:length(x),function(n)r [n] 用户系统消耗
11.36 0.00 11.39
>
> r< - NA
>系统时间(r 用户系统消耗
0.01 0.00 0.01
I have a vector containing simple time series data (extracted from a deSolve matrix), which for testing purposes can be:
x <- c(1, 2, 3, 4, 5)
and would like to apply the nonlinear filter
x[n]*x[n]-x[n-1]*x[n+1]
to all elements of the vector except the first and last elements because the filter can't be applied to these two elements (e.g., when the x[n-1]
term meets the first element or the x[n+1]
term meets the last element). Therein lies my problem.
Things I've tried:
1) The filter()
command expects a linear filter (i.e., without multiplication of filter coefficients).
2) lapply()
requires that the function applies to all elements of the list.
Is a loop the only alternative?
Thanks for your help, Carey
Can do it with loop or apply or vectorized.
> x <- c(1, 2, 3, 4, 5)
> r <- NA
> for (n in 2:length(x)) r[n] <- x[n]*x[n]-x[n-1]*x[n+1]
> (r)
[1] NA 1 1 1 NA
>
> r <- NA
> lapply(2:length(x),function(n) r[n] <<- x[n]*x[n]-x[n-1]*x[n+1])
[[1]]
[1] 1
[[2]]
[1] 1
[[3]]
[1] 1
[[4]]
[1] NA
> (r)
[1] NA 1 1 1 NA
> r <- NA
> r <- x^2 - c(NA,x[1:(length(x)-1)]) * c(x[2:length(x)],NA)
> (r)
[1] NA 1 1 1 NA
vectorization is the most efficient but code is harder to decipher
> x <- runif(50000)
>
> r <- NA
> system.time(for (n in 2:length(x)) r[n] <- x[n]*x[n]-x[n-1]*x[n+1])
user system elapsed
8.55 0.01 8.58
>
> r <- NA
> system.time(lapply(2:length(x),function(n) r[n] <<- x[n]*x[n]-x[n-1]*x[n+1]))
user system elapsed
11.36 0.00 11.39
>
> r <- NA
> system.time(r <- x^2 - c(NA,x[1:(length(x)-1)]) * c(x[2:length(x)],NA))
user system elapsed
0.01 0.00 0.01