[R] coding logic and syntax in R

Eric Lecoutre lecoutre at stat.ucl.ac.be
Wed Dec 24 09:09:58 CET 2003


In R, always begin to try to obtain result on a little unit.
Begin to make a function that will make replacements for ONE vector (of size 9)

FillWith=function(vec,SearchForOne=0,ReplaceNextValues=0)
{
  pp=which(vec==SearchForOne)
if (length(pp)>0) vec[pp:length(vec)]=ReplaceNextValues
return(vec)
}

Verify it works:

 > FillWith(c(1,1,0,1,1))
[1] 1 1 0 0 0


Then try to apply it with your data, using one of the ?apply functions.
Here, tapply seems to be adequate.

 > data=c(rep(1,9),rep(1,4),0,rep(1,4))
 > data
  [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1
 > data=cbind(data,groups=((1:length(data)-1)%/%9))
 > data
       data groups
  [1,]    1      0
  [2,]    1      0
  [3,]    1      0
  [4,]    1      0
  [5,]    1      0
  [6,]    1      0
  [7,]    1      0
  [8,]    1      0
  [9,]    1      0
[10,]    1      1
[11,]    1      1
[12,]    1      1
[13,]    1      1
[14,]    0      1
[15,]    1      1
[16,]    1      1
[17,]    1      1
[18,]    1      1

 > tapply(data[,1],data[,2],FUN=FillWith)
$"0"
[1] 1 1 1 1 1 1 1 1 1

$"1"
[1] 1 1 1 1 0 0 0 0 0

And then come back to a vector with unlist().

Eric




At 08:27 24/12/2003, Pravin wrote:
>Hello,
>
>
>I am a beginner in R programming and recently heard about this mailing list.
>Currently, I am trapped into a simple problem for which I just can't find a
>solution. I have a huge dataset (~81,000 observations) that has been
>analyzed and the final result is in the form of 0 and 1(one column).
>
>I need to write a code to process this column in a little complicated way.
>
>These 81,000 observations are actually 9,000 sets (81,000/9).
>
>So, in each set whenever zero appears, rest all observations become zero.
>
>For example;
>If the column has:
>111110111111011111111111111111111....
>The output should look like:
>111110000111000000111111111111111...
>I hope this makes sense.
>Thank you in anticipation,
>
>Pravin
>
>Pravin Jadhav



--------------------------------------------------
L'erreur est certes humaine, mais un vrai désastre
nécessite un ou deux ordinateurs. Citation anonyme
--------------------------------------------------
Eric Lecoutre
Informaticien/Statisticien
Institut de Statistique / UCL

TEL (+32)(0)10473050       lecoutre at stat.ucl.ac.be
URL http://www.stat.ucl.ac.be/ISpersonnel/lecoutre




More information about the R-help mailing list