[R] adding a dummy variable...

grazia at stat.columbia.edu grazia at stat.columbia.edu
Tue Oct 4 17:44:31 CEST 2011


Hi all,

I have a dataset of individuals where the variable ID corresponds to the
identification of the household where the individual lives. rel.head stands
for the relationship with the household head. so rel.head=1 is the household
head, rel.head=2 is the spouse, rel.head=3 is the children.

Here is an example to see how it looks like:

df<-data.frame(ID=c("17100", "17100", "17101", "17102", "17103", "17103",
                     "17104", "17104", "17104", "17105", "17105"),
  rel.head=c("1","3","1","1","1", "2", "1", "2", "3", "1", "3"))


I want to add a dummy variable that is equal to 1 when these conditions
held simultaneously :

a) the number of rows with same ID is equal to 2
b) the variable rel.head=1 and rel.head=3


So my ideal output is:

   ID      rel.head   added.dummy
1  17100        1           1
2  17100        3           1
3  17101        1           0
4  17102        1           0
5  17103        1           0
6  17103        2           0
7  17104        1           0
8  17104        2           0
9  17104        3           0
10 17105        1           1
11 17105        3           1

Is there a simple way to do that?
Can somebody help?

Thanks in advance,
Grazia



More information about the R-help mailing list