[R] help with Loop

Rui Barradas ruipbarradas at sapo.pt
Mon Jul 23 13:49:52 CEST 2012


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:
> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list