R中嵌套的'ifelse'语句
我有以下格式的数据,并试图创建一个新的变量,包括每次观察的死亡总数,其中存在表示正在发生的事件:R中嵌套的'ifelse'语句,r,function,if-statement,for-loop,nested,R,Function,If Statement,For Loop,Nested,我有以下格式的数据,并试图创建一个新的变量,包括每次观察的死亡总数,其中存在表示正在发生的事件: Birth1 Death1 Birth2 Death2 Birth3 Death3 Birth4 Death4 Birth5 Death5 Birth6 Death6 1 1990 present 2 1984 1986 1986 present
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
我尝试了data$num.deathes提取表示死亡的列,然后在每一行中加上非NA、非空字符串和不等于present的元素数。没有使用任何软件包
Deaths <- data[grep("Death", names(data))]
rowSums(!is.na(Deaths) & Deaths != "" & Deaths != "present")
## A B C D
## 0 1 1 2
注意:最好在您的问题中显示dputdata的输出,以明确、重复地传达您的输入。如果没有这一点,您所拥有的和答案假设之间可能会有微小差异,因此为了再现性的目的,我们将其用作输入,与修订前问题中显示的原始输入数据和样本输出相对应:
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"))
这里是另一个使用Reduce和+。我们使用lappy循环遍历列,通过检查元素是否只包含not的数量,将元素转换为二进制0/1,然后使用Reduce汇总每行的相应元素
Reduce(`+`,lapply(data[grep('Death', names(data))],
grepl, pattern='^\\d+$'))
#[1] 0 1 1 2
注意:该示例取自@G.Grothendieck的帖子中的dput输出。您可以dput您的数据,或者至少是您的数据头。请使用dput共享您的数据。这不是你的数据是矩阵还是数据框,它是什么类别,等等。你的数据中的空白是吗?例如,观察a和出生2 NA?如果数据列中缺少值,则不能直接使用ifelse中的逻辑函数。因此,不要共享全部内容!执行类似于dputdroplevelsdata[1:6,1:6]的操作,但选择一些说明问题的行和列。dput有什么问题?
> data
Birth1 Death1 Birth2 Death2 Birth3 Death3
A 1990 present NA NA
B 1984 1986 1986 present NA
C 1985 1988 1988 present NA
D 1987 1991 1991 1994 1996 present
Reduce(`+`,lapply(data[grep('Death', names(data))],
grepl, pattern='^\\d+$'))
#[1] 0 1 1 2