[R-sig-eco] change values of a vector selectively
Mathieu Basille
basille at ase-research.org
Tue Jan 11 19:36:12 CET 2011
What about something along that line? It implies converting into numeric
and then back to factor to take benefit of each class:
(bli <- factor(c(1, 0,0,0,0,0, 2,0,0,0,0,0, "A", 0,0,0,0,2, 0,0,0,1)))
blo <- ifelse(bli != 0, as.numeric(bli), 0)
bla <- factor(cumsum(blo))
levels(bla) <- bli[bli != 0]
bla
You can remove the 'blo' step and doing the whole stuff in one line
(factor(cumsum(ifelse(...)))), but I thought it was easier to understand
that way. I haven't tested on a large dataset if it's more efficient
than the 'for' approach, though.
Hope this helps,
Mathieu.
Le 2011-01-11 09:58, B.-Markus Schuller a écrit :
> Hey,
>
> I have a vector containing mostly zeroes. At varying positions are
> markers that mark different channels ("B", 1, 2).
>
>> head(exp$Marker, 100)
> [1] "B" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
> "0" "0"
> [19] "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
> "0" "0"
> [37] "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
> "0" "0"
> [55] "0" "0" "0" "0" "0" "1" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
> "0" "0"
> [73] "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
> "0" "0"
> [91] "0" "0" "0" "0" "0" "0" "0" "0" "0" "0"
>
> I would like to change all zeroes between two markers to the marker that
> came before.
> E.g. everything after "B" shall be "B" until the 1. Then everything
> shall be 1 until the next "B" and so on. I hope you can imagine what I
> intend.
>
> I tried it in a loop:
>
> for(i in 1:length(exp$Marker)){
> if(! exp$Marker[i] %in% c("B", 1, 2))
> exp$Marker[i] <- exp$Marker[i-1]
> }
>
> but that takes forever. Can anyone point me to another solution?
> E.g. identify all so far not marked elements, like this
>
> exp$Marker[which(! exp$Marker %in% c("B", 1, 2))]
>
> and change them to the desired values. But i cannot figure out how to
> change them selectively...
>
> Thanks for your help!
>
> Cheers,
> Mango
--
~$ whoami
Mathieu Basille, Post-Doc
~$ locate
Laboratoire d'Écologie Comportementale et de Conservation de la Faune
+ Centre d'Étude de la Forêt
Département de Biologie
Université Laval, Québec
~$ info
http://ase-research.org/basille
~$ fortune
``If you can't win by reason, go for volume.''
Calvin, by Bill Watterson.
More information about the R-sig-ecology
mailing list