【问题标题】:conditional replacement of a value for a column of a specific row of a data frame with sum of specific rows用特定行的总和有条件地替换数据框特定行的列的值
【发布时间】:2015-08-04 15:33:18
【问题描述】:

我一直在为我的数据框在 R 中进行聚合/求和。我的数据如下:

    hour    Case   Time
       7       2    35
       8       8    125
       9       10   145
       10      15   18
       11      17   167
       12      20   220
       13      25   135
       14      14   167
       15      18   134
       16      16   100
       17      7    55
       18      6    178
       19      5    245
       20      1    133
       21      1    12
       22      0    54
       23      2    180
       24      1    55

我只想用“小时” 18 . 我在 R 中尝试了条件聚合()、with()、colsums() 函数,但它们都不起作用。不知道是否有人能给我提示。

谢谢

【问题讨论】:

  • @akrun 忘记删除。我编辑了帖子
  • 您仍然应该提供预期的输出。
  • df[df$hour == 8, c("Case", "Time")] <- colSums(df[df$hour <= 8 | df$hour > 18, c("Case", "Time")])?
  • @DavidArenburg 非常感谢。效果很好。
  • 好的,作为答案发布以关闭此问题。

标签: r sum aggregate


【解决方案1】:

您可以尝试条件colSums,同时按条件分配给原始数据集

df[df$hour == 8, c("Case", "Time")] <- colSums(df[df$hour <= 8 | df$hour > 18, c("Case", "Time")])

【讨论】:

    猜你喜欢
    • 2016-06-20
    • 2020-02-24
    • 1970-01-01
    • 2019-02-03
    • 2017-05-06
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多