代码之家  ›  专栏  ›  技术社区  ›  jakes

如何按可变行数偏移行

  •  1
  • jakes  · 技术社区  · 7 年前

    数据如下:

    data <- structure(list(seq_grp = 1:40, n_offset = c(1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 3, 2, 1, 1, 3, 2, 1, 1, 1, 1, 3, 2, 1, 1, 7, 6, 5, 
    4, 3, 2, 1, 1, 9, 8, 7, 6, 5, 4, 3, 2)), row.names = c(NA, -40L
    ), class = c("tbl_df", "tbl", "data.frame"))
    

    我想创建一个新列,其中以下行中的值将具有 seq_grp 但长度偏移由 n_offset dplyr::mutate(new = dplyr::lead(seq_grp, n = n_offset)) 会有用的,但是 lead 只接受标量。

    2 回复  |  直到 7 年前
        1
  •  2
  •   akrun    7 年前

    一个选项 dplyr

    library(dplyr)
    data %>%
       mutate(new_sq = seq_grp[row_number() + n_offset])
    
        2
  •  1
  •   Nate xin ding    7 年前

    不是的 dplyr 但是只要 baseR 你可以这样做:

    data$new_sq <- data$seq_grp[1:nrow(data) + data$n_offset]
    
    data$new_sq
    
    [1]  2  3  4  5  6  7  8  9 10 11 14 14 14 15 18 18 18 19 20 21 24 24 24 25 32 32 32 32 32 32 32 33 NA NA NA NA
    [37] NA NA NA NA
    
        3
  •  0
  •   Bryan Shalloway    6 年前

    答案类似于@akrun,但处理带有偏移量的索引不存在的边大小写。

    library(tidyverse)
    set.seed(1234)
    df <- tibble(x = letters, offset = c(-1, sample(-3:3, 24, replace = TRUE), 1))
    
    offset_pos <- function(x, offset){
      seq_x <- seq_along(x)
      pos_start <- seq_x  + offset
      pos_final <- if_else(pos_start %in% seq_x, pos_start, NA_real_)
      x[pos_final]
    }
    
    df %>% 
      mutate(new_x = offset_pos(x, offset))
    #> # A tibble: 26 x 3
    #>    x     offset new_x
    #>    <chr>  <dbl> <chr>
    #>  1 a         -1 <NA> 
    #>  2 b         -3 <NA> 
    #>  3 c          1 d    
    #>  4 d          1 e    
    #>  5 e          1 f    
    #>  6 f          3 i    
    #>  7 g          1 h    
    #>  8 h         -3 e    
    #>  9 i         -2 g    
    #> 10 j          1 k    
    #> # ... with 16 more rows
    

    reprex package

    推荐文章