IF ELSE语句中的多个操作

时间:2017-10-12 17:40:56

标签: r

示例数据框如下所示:

df = data.frame(a=1:5, b=11:15)
a  b
1 11
2 12
3 13
4 14
5 15

如何使用if else语句在数据框中创建新列c和d? 我希望输出看起来像这样:

a b    c    d
1 11 'yes'  22
2 12 'yes'  24
3 13 'yes'  26
4 14 'no'   14
5 15 'no    15

我根据(If statement with multiple actions in R)尝试了这个!

for (i in nrow(df)){
  if (df$a[i] <4) {
    df$c[i] = 'yes'; 
    df$d[i] = df$b[i]*2;
    df
  } else {
    df$c[i] = 'no'; 
    df$d[i] = df$b[i];
    df
  }
}

但输出只提供最后一行:

 a  b   c  d
 1 11 <NA> NA
 2 12 <NA> NA
 3 13 <NA> NA
 4 14 <NA> NA
 5 15   no 15

提前致谢。

1 个答案:

答案 0 :(得分:1)

使用_context.Name.AsExpandable().Where(n => n.CastInfo.Any(c => castCondition.ToExpression().Invoke(c))); 的另一个矢量化解决方案:

ifelse()