# [R] computing sum of indicator variables

Berton Gunter gunter.berton at gene.com
Mon Jul 26 18:24:56 CEST 2004

```Think whole objects!

Simpler and quicker would be:

y<-rep(0,max(i))
y[i]<-1

would it not?

Cheers,
Bert

--

Bert Gunter

Non-Clinical Biostatistics
Genentech
MS: 240B
Phone: 650-467-7374

"The business of the statistician is to catalyze the scientific learning
process."

-- George E.P. Box

Dimitris Rizopoulos wrote:

> Hi Stefan,
>
> you could try something like,
>
> x <- c(2,4,7)
> as.numeric(!is.na(match(seq(1, max(x)), x)))
>
> I hope this helps.
>
> Best,
> Dimitris
>
> ----
> Dimitris Rizopoulos
> Doctoral Student
> Biostatistical Centre
> School of Public Health
> Catholic University of Leuven
>
> Address: Kapucijnenvoer 35, Leuven, Belgium
> Tel: +32/16/396887
> Fax: +32/16/337015
> Web: http://www.med.kuleuven.ac.be/biostat/
>      http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm
>
> ----- Original Message -----
> From: "Stefan Böhringer" <commercial at s-boehringer.de>
> To: "R Help" <r-help at stat.math.ethz.ch>
> Sent: Monday, July 26, 2004 10:45 AM
> Subject: [R] computing sum of indicator variables
>
> > My problem is as follows:
> > i is a list of integers of variable length. Now I want to compute a
> new
> > vector/array that contains 1's at the positions indicated in i. For
> > example:
> > c(2, 4) -> c(0, 1, 0, 1)
> >
> > Using something like
> > i = i - c(0, i[2:length(i) - 1]);
> > sapply(i, function(x) c(rep(0, x - 1), 1)));
> >
> > faces me with the problem of concatenating the result, which I could
> > somehow not find a solution for.
> >
> > Thank you very much in advance.
> >
> > Stefan
> >

```