[R-sig-eco] change values of a vector selectively

syrovat at sci.muni.cz syrovat at sci.muni.cz
Tue Jan 11 16:42:42 CET 2011


Hi Mango,
If I understand it well, the following loop should do the work. I include
a small example.

a<- c(1,0,0,0,'A',0,0,0,2,0,0,0,1,0,0,0,0,2,0,0,0,1)

for(i in (1:length(a)-1)){
  if (a[i+1]==0) a[i+1]<-a[i]}

a
 [1] "1" "1" "1" "1" "A" "A" "A" "A" "2" "2" "2" "2" "1" "1" "1" "1" "1"
"2" "2" "2" "2" "1"

Cheers,
Vit

--
Vit Syrovatka
Department of Botany and Zoology
Masaryk University
Kotlarska 2
CZ-611 37 Brno, Czech Republic

Tel.: +420-532146342
E-mail: syrovat at sci.muni.cz

> 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
> --
> -----------------------------------------
> B.-Markus Schuller aka Mango
>
> Sensory Ecology Group
> Max-Planck-Institute for Ornithology
> 82319 Seewiesen, Germany
>
> phone: +49 (0)8157 932 -378
> fax:   +49 (0)8157 932 -344
> email: schuller at orn.mpg.de
> http://www.orn.mpg.de/nwg/abtsiemers.html
> -----------------------------------------
> Never run for the bus.
> Never skip tea.
>
>
>
> -----
> No virus found in this message.
> Checked by AVG - www.avg.com
>
> _______________________________________________
> R-sig-ecology mailing list
> R-sig-ecology at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-ecology
>



More information about the R-sig-ecology mailing list