So I have a time series of MODIS NDVI values (vegetation values from 0-1 for the non-geographic geeks), and I'm trying to approximate the derivative by using a for
loop.
This is a sample of my data:
> m2001
date value valnorm
1 1 0.4834 0.03460912
2 17 0.4844 0.03664495
3 33 0.5006 0.06962541
4 49 0.4796 0.02687296
5 65 0.5128 0.09446254
6 81 0.4915 0.05109935
7 97 0.4664 0.00000000
8 113 0.5345 0.13864007
9 129 0.8771 0.83611564
10 145 0.9529 0.99043160
11 161 0.9250 0.93363192
12 177 0.9450 0.97434853
13 193 0.9491 0.98269544
14 209 0.9434 0.97109121
15 225 0.9576 1.00000000
16 241 0.8992 0.88110749
17 257 0.9115 0.90614821
18 273 0.8361 0.75264658
19 289 0.5725 0.21600163
20 305 0.5188 0.10667752
21 321 0.5467 0.16347720
22 337 0.5484 0.16693811
23 353 0.5427 0.15533388
I'm still very new to programming and R, but I think I've managed to piece together a tenuous grasp on it. What I'm trying to do is create a new column with values that would give me some idea of the local slope of data points.
The function I've come up with is this:
deriv <- function(x1=1:23, x2=1){
for (i in x1){
i1 <- c(x1[i-1], x1[i], x1[i+1])
i2 <- c(x2[i-1], x2[i], x2[i+1])
deriv.func <- lm(i2~i1, na.action=NULL)
} return(deriv.func$coef[[2]])
}
What happens when I run it is this:
> deriv <- function(x1=1:23, x2=1){
+ for (i in x1){
+ i1 <- c(x1[i-1], x1[i], x1[i+1])
+ i2 <- c(x2[i-1], x2[i], x2[i+1])
+ deriv.func <- lm(i2~i1, na.action=NULL)
+ } return(deriv.func$coef[[2]])
Error: unexpected symbol in:
"deriv.func <- lm(i2~i1, na.action=NULL)
} return"
> }
Error: unexpected '}' in "}"
>
I'm not sure what I'm doing wrong, as I can get it to parse when I fill in a value for i
> i=6
> x1=m2001$date
> x2=m2001$valnorm
> i1 <- c(x1[i-1], x1[i], x1[i+1])
> i2 <- c(x2[i-1], x2[i], x2[i+1])
> i1
[1] 33 49 65
> i2
[1] 0.06962541 0.02687296 0.09446254
> lm(i2 ~ i1)
Call:
lm(formula = i2 ~ i1)
Coefficients:
(Intercept) i1
0.0256218 0.0007762
> func <- lm(i2 ~ i1)
> func$coef[[2]]
[1] 0.0007761604
Any ideas? Thanks a ton.
Well, after looking (a lot) more into the for
loop, I got it to do what I want.
deriv <- function(x1=1:23, x2=1){
n=length(x1)
deriv.func <- character(length = n)
for (i in 1:n) {
i1 <- c(x1[i-1], x1[i], x1[i+1])
i2 <- c(x2[i-1], x2[i], x2[i+1])
derivate <- lm(i2~i1)
deriv.func[i] <- derivate$coef[[2]]*
}
return(deriv.func)
}
Thanks for the help, and the tip in the right direction, @dbaseman!
Ideas that made a difference:
deriv.func <-
character(length = n)
.