【问题标题】:Column that tracks when the value in another column changes [duplicate]跟踪另一列中的值更改时的列[重复]
【发布时间】:2021-03-30 20:05:49
【问题描述】:

我的数据子集:

library(tidyverse)

df <- structure(list(Score = c(18, 18, 20, 20, 19, 19, 19, 19, 19, 
19, 19, 19, 19, 17, 17, 17, 17, 17, 19, 19)), row.names = c(NA, 
-20L), class = c("tbl_df", "tbl", "data.frame"))

我想创建一个列来跟踪分数从 = 19 或反之亦然。

我目前正在尝试这个:

df %>%
  mutate(temp = as.numeric(Score < 19))

Score temp
18  1           
18  1           
20  0           
20  0           
19  0           
19  0           
19  0           
19  0           
19  0           
19  0
19  0           
19  0           
19  0           
17  1           
17  1           
17  1           
17  1           
17  1           
19  0           
19  0   

但是,我想要看起来像这样的东西:

Score temp
18  1           
18  1           
20  2           
20  2           
19  2           
19  2           
19  2           
19  2           
19  2           
19  2
19  2           
19  2           
19  2           
17  3           
17  3           
17  3           
17  3           
17  3           
19  4           
19  4   

非常感谢任何帮助。

编辑:最终使用this post

【问题讨论】:

  • 正如@Henrik 所说:data.table::rleid(df$Score &gt;= 19)

标签: r


【解决方案1】:

使用rle

with(rle(df$Score >= 19), rep(seq_along(values), lengths))
#[1] 1 1 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 4 4

【讨论】:

    【解决方案2】:

    另一个使用 cumsum + diff 的基本 R 选项

    transform(
      df,
      temp = cumsum(c(1, diff(Score >= 19) != 0))
    )
    

    给予

       Score temp
    1     18    1
    2     18    1
    3     20    2
    4     20    2
    5     19    2
    6     19    2
    7     19    2
    8     19    2
    9     19    2
    10    19    2
    11    19    2
    12    19    2
    13    19    2
    14    17    3
    15    17    3
    16    17    3
    17    17    3
    18    17    3
    19    19    4
    20    19    4
    

    【讨论】:

      猜你喜欢
      • 2010-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 1970-01-01
      • 2015-01-17
      • 2021-11-09
      • 2015-12-06
      相关资源
      最近更新 更多