【问题标题】:Select rows with incremental column value选择具有增量列值的行
【发布时间】:2021-08-06 06:40:51
【问题描述】:

我有这样的数据:

SNP  chr pos   
 A1    1   2 
 A2    1   3   
 A3    1   4  
 A4    1 4.5
 A5    1   6

我的真实数据更大,有几个不同的“chr”。

我想根据 'pos' 列值以恒定增量(比如说 2)选择行。如果我选择 A1,然后我的下一个选择是 A3,然后是 A5,这意味着差异 2 是固定的,并且有一段时间它可能在 2 左右。

我尝试了dplyr::between,但我没有成功。

filter(df, between(pos, 2, 4))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:
    library(tidyverse)
    ## I've extended the sample data for experimenting with the desired output
    SNP <- paste0('A', 1:10)
    chr <- rep(1, 10)
    pos <- c(2, 3, 4, 4.5, 6, 7, 8, 9, 11, 12) ## Asuming there are no duplicate values
    df <- cbind.data.frame(SNP, chr, pos)
    
    ## Create a helper function to generate the possible incremental value
    selector <- function(start_val, end_val, increment){
      return(seq(start_val, end_val, by = increment))
    } 
    
    ## initiate start_val & increment as per your choice
    start_val <- 2
    increment <- 2
      
    
    df_filtered <- df %>%
      filter(pos %in% selector(start_val, end_val = start_val * n(), increment)) %>%
      arrange(pos) %>%
      mutate(checkpoint = start_val + increment * (row_number() -1),
             id = row_number()) %>%
      filter(id < (
        if_else(sum(FALSE == (pos == checkpoint)) > 0,
                which((pos == checkpoint) == FALSE)[1], (n() + 1L)
                ))) %>%
        select(SNP:pos)
      
    df_filtered
    

    【讨论】:

    • Forhad Excellant 您的解决方案可以根据我的需要工作非常感谢您的帮助:)
    【解决方案2】:

    你可以使用seq函数-

    n <- 2
    start_row <- 1
    result <- df[seq(start_row, nrow(df), n), ]
    result$SNP
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多