如何根据另一列的条件输出来创建两个累积列?

时间:2019-04-23 14:09:49

标签: r

我试图遍历数据框的行,并根据数据框的“结果”列在“获胜”或“损失”列中添加1。在每次通过代码循环之后,我都需要它来打印数据框行。

我尝试使用cumsum()函数,但我需要它以Result字符(胜或负)为条件,但每次都失败。我也尝试过for循环,而我最接近解决此问题的方法是打印出新数据集,并在“获胜者专栏”中进行总匹配。

for (row in 1:nrow(Dylan)) {
if( Dylan$Result == "Won") {Dylan$Won = Dylan$Won + 1}
else {Dylan$Lost = Dylan$Lost + 1}
}


Here are the errors I get:
In if (Dylan$Result == "Won") { ... :
the condition has length > 1 and only the first element will be used
2: In if (Dylan$Result == "Won") { ... :
the condition has length > 1 and only the first element will be used

我需要新的数据框来显示每个“获胜和损失”列的连续增加,因此各列在各行中增加,而不仅仅是显示每行获胜的总数和损失的总数。

1 个答案:

答案 0 :(得分:0)

完成这项工作:

for (row in 1:nrow(Dylan)) {
  if (Dylan$Result[row] == "Won") {
    Dylan$Won = Dylan$Won + 1
  } else {
    Dylan$Lost = Dylan$Lost + 1
  }
}