Select every nth row from dataframe

后端 未结 3 802
灰色年华
灰色年华 2020-11-28 09:41

I have a data table and want to extract every fifth row from it to create a new table. Is there a command to achieve this?

Here is an sample of my data:



        
相关标签:
3条回答
  • 2020-11-28 10:30

    For a data frame df, you can get df.new as:

    df.new = df[seq(1, nrow(df), 5), ]
    

    This creates an index from row 1 to nrow (number of rows of the table) every 5 rows. You can play with the starting point and the 5 to extract other sequences.

    0 讨论(0)
  • 2020-11-28 10:43

    If you want to extract 5,10...

    newdf <- df[c(rep(FALSE,4),TRUE), ]
    

    If 1,6,11,

    newdf <- df[c(TRUE,rep(FALSE,4)), ]
    
    0 讨论(0)
  • 2020-11-28 10:46

    One dplyr possibility for this task could be:

    df %>%
     slice(which(row_number() %% 5 == 1))
    
      count Idf_Nr block
    1     1   1233   B12
    2     6    365   B12
    3    11   1092   B12
    4    16   1266   B12
    5    21   1074   B12
    

    Or:

    df %>%
     filter(row_number() %% 5 == 1)
    
    0 讨论(0)
提交回复
热议问题