【问题标题】:Get names of first and last row for every run of 1每次运行 1 获取第一行和最后一行的名称
【发布时间】:2021-12-08 04:33:13
【问题描述】:

我有一个数据框,其中:

df <- data.frame(position = c(1000,1156,3200,4629,5559,6100,7456,8208,9500,10000),
     col1 = c(1,0,1,1,1,0,0,1,1,0))

我想创建一个单独的表来获取每次运行 1 的第一个和最后一个 position 的值。例如,此数据框的输出将是:

| first_position | last_position |
|  3200          |   5559        |
|  8208          |   9500        |

任何帮助将不胜感激,谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以尝试使用dplyr、data.table::rleid

    library(data.table)
    library(dplyr)
    
    df %>%
      mutate(key = rleid(col1)) %>%
      group_by(key) %>%
      filter(col1 == 1, n() > 1) %>%
      summarize(first_position = first(position),
                last_position = last(position)) %>%
      select(-key)
    
      first_position last_position
               <dbl>         <dbl>
    1           3200          5559
    2           8208          9500
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-29
      • 2014-11-10
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2021-04-06
      相关资源
      最近更新 更多