Select every nth row in the data frame

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

Here is an example 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
+11
source share
3 answers

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

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

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

+24
source

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)), ]
+7
source

One possibility dplyrfor 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
0
source

Source: https://habr.com/ru/post/1537961/


All Articles