Skip to content

help with Loop

2 messages · Katrin Ronnenberg, Rui Barradas

#
hello there,
I'm an R beginner and got plunged into this. I guess my attempts are hopeless so far, so I won't even show them.
I want to write a loop, which prints all erroneous values. My definition of erroneous: If the current counts (partridge counts in a hunting district) differ from last years counts by more than 50 percent and absolut values differ by more than 5 animals I want r to print these values.  

I have a grouping variable District "D", the year "Y" and the counts "C". 

example table:

D	Y	C
a	2005	10
a	2006	0
a	2007	9
b	2005	1
b	2006	0
b	2007	1
c	2005	5
c	2006	NA
c	2007	4

Although the difference in a and b is 100 percent I would doubt a's population breakdown, whereas District b is credible. To confuse things I want the loop to skip missing values and instead look at the year after. 
Any help is very much appreciated!
Thanks,
Katrin
#
Hello,

Try the following.


d <- read.table(text="
D Y C
a 2005 10
a 2006 0
a 2007 9
b 2005 1
b 2006 0
b 2007 1
c 2005 5
c 2006 NA
c 2007 4 ", header=TRUE)
d

prn <- lapply(split(d, d$D), function(x){
     x <- x[!is.na(x$C), ]
     x[c(FALSE, diff(x$C)/x$C[-length(x$C)] < -0.5 & diff(x$C) < -5), ]
})
do.call(rbind, prn)

Hope this helps,

Rui Barradas

Em 23-07-2012 11:08, Katrin Ronnenberg escreveu: