Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select every nth row from dataframe

Tags:

dataframe

r

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:

count   Idf_Nr  block 1   1233    B12 2   1233    B12 3   1446    B12 4   1446    B12 5   365 B12 6   365 B12 7   876 B12 8   876 B12 9   842 B12 10  842 B12 11  1092    B12 12  1092    B12 13  923 B12 14  923 B12 15  1266    B12 16  1266    B12 17  256 B12 18  256 B12 19  588 B12 20  588 B12 21  1074    B12 22  1074    B12 23  474 B12 24  474 B12 25  1421    B12 
like image 936
user3570605 Avatar asked Apr 24 '14 20:04

user3570605


People also ask

How do you select every nth row in Python?

To select every nth row of a DataFrame - we will use the slicing method. Slicing in pandas DataFrame is similar to slicing a list or a string in python. Suppose we want every 2nd row of DataFrame we will use slicing in which we will define 2 after two :: (colons).

How do you get every nth row in pandas?

To get the nth row in a Pandas DataFrame, we can use the iloc() method. For example, df. iloc[4] will return the 5th row because row numbers start from 0.

How do I keep every nth row in R?

Use stripe(n, from = m) to get every nth row/column starting at row/column m. Use dplyr functions like starts_with , contains and matches to specify columns (but not rows).


2 Answers

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.

like image 105
user14382 Avatar answered Sep 18 '22 22:09

user14382


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) 
like image 36
tmfmnk Avatar answered Sep 19 '22 22:09

tmfmnk