[R] function that calculates using preceding records

JS Huang js.huang at protective.com
Wed Feb 11 04:28:17 CET 2015


Hi,

  Here is an implementation:

> data <- read.table("tree.txt",header=TRUE,sep=",",stringsAsFactors=FALSE)
> data
   treecode year    rw     d
1     TC149 2014    NA    8 
2     TC149 2013 0.080   NA 
3     TC149 2012 0.125   NA 
4     TC149 2011 0.120   NA 
5     TC149 2010 0.125   NA 
6     TC148 2014    NA   34 
7     TC148 2013 0.300   NA 
8     TC148 2012 0.335   NA 
9     TC148 2011 0.315   NA 
10    TC148 2010 0.455   NA 
11    TC147 2014    NA 55.5 
12    TC147 2013 1.260   NA 
13    TC147 2012 1.115   NA 
14    TC147 2011 1.025   NA 
15    TC147 2010 1.495   NA 
16    TC146 2014    NA   60 
17    TC146 2013 1.750   NA 
18    TC146 2012 1.810   NA 
19    TC146 2011 1.390   NA 
20    TC146 2010 1.940   NA 
> calDiameter <- function(x)
+ {
+   temp <- x
+   for (i in 1:dim(temp)[1])
+   {
+     if (dim(x[x$treecode==temp$treecode[i] & x$year == temp$year[i] - 1  &
!is.na(x$rw),])[1] == 1 & !is.na(temp$d[i]))
+     {
+       temp$d[i] <- as.numeric(temp$d[i]) - as.numeric(x[x$treecode ==
temp$treecode[i] & x$year == temp$year[i] - 1 & !is.na(x$rw), ]$rw[1])
+     }
+   }
+   return(temp)
+ }
> calDiameter(data)
   treecode year    rw     d
1     TC149 2014    NA  7.92
2     TC149 2013 0.080  <NA>
3     TC149 2012 0.125  <NA>
4     TC149 2011 0.120  <NA>
5     TC149 2010 0.125   NA 
6     TC148 2014    NA  33.7
7     TC148 2013 0.300  <NA>
8     TC148 2012 0.335  <NA>
9     TC148 2011 0.315  <NA>
10    TC148 2010 0.455   NA 
11    TC147 2014    NA 54.24
12    TC147 2013 1.260  <NA>
13    TC147 2012 1.115  <NA>
14    TC147 2011 1.025  <NA>
15    TC147 2010 1.495   NA 
16    TC146 2014    NA 58.25
17    TC146 2013 1.750  <NA>
18    TC146 2012 1.810  <NA>
19    TC146 2011 1.390  <NA>
20    TC146 2010 1.940   NA 
There were 12 warnings (use warnings() to see them)



--
View this message in context: http://r.789695.n4.nabble.com/function-that-calculates-using-preceding-records-tp4703024p4703069.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list