mardi 2 février 2016

Nested `ifelse` statements in R

I have data in the following format:

        Birth1  Death1  Birth2  Death2  Birth3  Death3
 A      1990    present             
 B      1984    1986    1986    present     
 C      1985    1988    1988    present     
 D      1987    1991    1991    1994    1996    present

and am trying to create a new variable that includes the total number of deaths for each observation, where "present" indicates an ongoing event:

        Number_of_Deaths
 A      0
 B      1
 C      1
 D      2

I tried data$num.deaths <- ifelse(data$death1=="present", 0, 1) but obviously that doesn't get at the observations that have more than one death event. I also tried nested ifelse but got the same result. Can anybody point me to a fast and efficient way of doing this?

EDIT: here is the summary from head(dataset):

   Band.ID           Band       Country                        Location    Status Formed Active_From
 1       1       Amorphis       Finland                        Helsinki  Active   1990        1990
 2       2 Blind Guardian       Germany Krefeld, North Rhine-Westphalia  Active   1986        1984
 3       3     Iced Earth United States                  Tampa, Florida  Active   1988        1985
 4       4      Katatonia        Sweden                       Stockholm  Active   1991        1987
 5       5       Entombed        Sweden                       Stockholm On hold   1989        1987
    Birth1                       Death1 Birth2  Death2 Birth3  Death3 Birth4 Death4 Birth5 Death5
 1   1990                      present     NA             NA             NA     NA     NA     NA
 2   1984 1986 (as Lucifer's Heritage)   1986 present     NA             NA     NA     NA     NA
 3   1985          1988 (as Purgatory)   1988 present     NA             NA     NA     NA     NA
 4   1987       1991 (as Melancholium)   1991    1994   1996 present     NA     NA     NA     NA
 5   1987           1989 (as Nihilist)   1989    2014     NA             NA     NA     NA     NA
   Birth6 Death6
 1     NA     NA
 2     NA     NA
 3     NA     NA
 4     NA     NA
 5     NA     NA

Aucun commentaire:

Enregistrer un commentaire