2

Let's say I have the following data set

1 2 3 4
4 5 6 7
2 3 4 6
3 4 5 6 
9 4 8 6 
4 4 5 6
3 2 1 5
4 3 2 1
9 9 8 8
.
.
.

Now I want to work with these rows:

   1 2 3 4
   9 4 8 6
   9 9 8 8
    .
    .
    .

In other words I take the first row and then I miss 3 rows and have the fourth one again miss 3 rows and have the seventh one and ...

4 Answers4

2

We can use:

df[seq(1,nrow(df),4),]
  V1 V2 V3 V4
1  1  2  3  4
5  9  4  8  6
9  9  9  8  8

Data:

df<-structure(list(V1 = c(1L, 4L, 2L, 3L, 9L, 4L, 3L, 4L, 9L), V2 = c(2L, 
5L, 3L, 4L, 4L, 4L, 2L, 3L, 9L), V3 = c(3L, 6L, 4L, 5L, 8L, 5L, 
1L, 2L, 8L), V4 = c(4L, 7L, 6L, 6L, 6L, 6L, 5L, 1L, 8L)), class = "data.frame", row.names = c(NA, 
-9L))
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    I was going for the same solution. But don't you mean df[seq(1,nrow(df),**3**),] ? –  Jun 03 '19 at 13:18
  • Ideally it should be 3 from OP's description, but there output actually skips 4 and not 3 rows or perhaps it's to do with R's arrays starting from 1(frankly, I'm not sure why 4 and not 3 works). – NelsonGon Jun 03 '19 at 13:18
1

A different dplyr possibility could be:

df %>%
 slice(which(row_number() %% 4 == 1))

  V1 V2 V3 V4
1  1  2  3  4
2  9  4  8  6
3  9  9  8  8
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
0

We can create a custom grouping variable and get the first entry of each group. A solution in tidyverse would be,

library(dplyr)

df %>% 
 group_by(grp = c(0, rep(1:(n() - 1) %/% 4))) %>% 
 slice(1L)

which gives,

# A tibble: 3 x 5
# Groups:   grp [3]
     V1    V2    V3    V4   grp
  <int> <int> <int> <int> <dbl>
1     1     2     3     4     0
2     9     4     8     6     1
3     9     9     8     8     2
Sotos
  • 51,121
  • 6
  • 32
  • 66
0

Yet another solution is

df[1:nrow(df) %% 4 == 1, ]
  V1 V2 V3 V4
1  1  2  3  4
5  9  4  8  6
9  9  9  8  8