[R] For loop by factor.

Sarah Goslee sarah.goslee at gmail.com
Mon Jun 20 01:02:01 CEST 2011


This works, but I'm still hunting for a more elegant final step:
> test <- data.frame(A=c("a", "a", "a", "b", "b", "c", "c", "c", "c"), B=c(3,2,1,3,2,2,3,1,1))
> test2 <- lapply(split(test$B, test$A), sort, dec=TRUE)
> test3 <- data.frame(A=rep(names(test2), times=lapply(test2, length)), B=unlist(test2))

It will also group data by factor, which was already done in your example.

Sarah

On Sun, Jun 19, 2011 at 4:20 PM, Christopher Peters <cpeter9 at lsu.edu> wrote:
> I have a data.frame as follows:
>
> a  3
> a  2
> a  1
> b  3
> b  2
> c  2
> c  3
> c  1
> c  1
>
> Each factor (a, b, c) should be monotonically decreasing, notice that factor
> 'c' is not.
>
> I could use some help to figure out how to form a logical structure (mostly
> just syntax), that will check each 'next value' for each factor to see if it
> is less than the previous value.  If it is less than the previous value, do
> nothing, else subtract 'next value' from 'current value', add that amount to
> the starting value and each previous value to the 'next value' is greater
> than 'previous value'.
>
> So basically the data.frame would look like:
>
> a 3
> a 2
> a 1
> b 3
> b 2
> c 3
> c 3
> c 1
> c 1
>
-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list