function - Nested `ifelse` statements in R -
i have data in following format , trying create new variable includes total number of deaths each observation, "present" indicates ongoing event:
birth1 death1 birth2 death2 birth3 death3 birth4 death4 birth5 death5 birth6 death6 1 1990 present 2 1984 1986 1986 present 3 1985 1988 1988 present 4 1987 1991 1991 1994 1996 present 5 1987 1989 1989 present
i tried data$num.deaths <- ifelse(data$death1=="present", 0, 1)
doesn't @ observations have more 1 death event. tried nested ifelse got same result. can point me fast , efficient way of doing this?
extract columns represent deaths giving deaths
, in each row add number of elements not na, not empty strings , not equal "present"
. no packages used.
deaths <- data[grep("death", names(data))] rowsums(!is.na(deaths) & deaths != "" & deaths != "present") ## b c d ## 0 1 1 2
an alternative last line of code gives same result check each cell of each row having numeric , add successes in each row -- apply
turns rows columns use colsums
that.
colsums(apply(deaths, 1, grepl, pattern = "\\d"))
note: it's best show output of dput(data)
in question unambiguously , reproducibly convey input. without there small differences between have , answers assume purposes of reproducibility used input (which corresponds original input data , sample output shown in question before revised):
data <- structure(list(birth1 = c(1990l, 1984l, 1985l, 1987l), death1 = c("present", "1986", "1988", "1991"), birth2 = c(na, 1986l, 1988l, 1991l), death2 = c("", "present", "present", "1994"), birth3 = c(na, na, na, 1996l), death3 = c("", "", "", "present")), .names = c("birth1", "death1", "birth2", "death2", "birth3", "death3"), class = "data.frame", row.names = c("a", "b", "c", "d"))
it looks this:
> data birth1 death1 birth2 death2 birth3 death3 1990 present na na b 1984 1986 1986 present na c 1985 1988 1988 present na d 1987 1991 1991 1994 1996 present
Comments
Post a Comment