【问题标题】:An If Statement inside an applyapply 中的 If 语句
【发布时间】:2026-02-13 12:20:02
【问题描述】:

我正在尝试使用 apply() 逐行遍历数组,查看 1 和 0 的列,然后如果第一列是 1,则使用函数填充同一数组中的另一列,并且如果为 0,则为不同的函数。

所以它会像......

apply(OutComes, 1, if(risk = 1) {OutComes[, "Age"] = Function_1} else{OutComes[, "Age"] = Function_2} )

OutComes 是有问题的数组, risk 是决定我们使用哪个函数的变量。

目的是两个功能决定寿命,人属于这两个类别之一,每个类别都有自己的功能。根据风险组,我想使用不同的函数来计算年龄,但这似乎不起作用。

【问题讨论】:

  • 我觉得ifelse在这里可能比较合适

标签: arrays r function if-statement apply


【解决方案1】:

apply() 需要函数名;你需要在这里定义一个函数, 因为没有提供现成的功能。

示例:apply(OutComes, 1, sum) - 将返回每行的总和。 vector 中输出的数量与 number 或 rows 相同,因此您可以将其分配给变量,然后通过 cbind 添加或替换现有列的值。

apply(OutComes, 1, function(x) { 
  if (x[n] == 1) {
    Function_1 ()
  }else {
    Function_2 ()
    } ) -> new_age
# x : is the working row at the time
# n : column number for "risk" # or # if(x["risk"] ==1)
# also note == instead of = at if 
OutComes = cbind(OutComes, new_age)
#or
OutComes$Age <- new_age

【讨论】: