Home > Software design >  Extract some rows in the matrix at fixed intervals?
Extract some rows in the matrix at fixed intervals?

Time:06-22

How to extract two rows every three rows of the following matrix?

simple <- matrix(1:300,nrow=50,ncol=4)

CodePudding user response:

Another similar option

2 every 3

k=2
skp=3

unlist(sapply(seq(1,nrow(simple),k skp),function(x){x:(x k-1)},simplify=F))
[1]  1  2  6  7 11 12 16 17 21 22 26 27 31 32 36 37 41 42 46 47

7 every 3

k=7
skp=3

CodePudding user response:

Edit: generate a certain sequence

Generate the sequence you want to subset the rows like this:

rows <- sort(c(seq(1,nrow(simple), 5), seq(2,nrow(simple), 5)))
simple[rows,]

Output:

      [,1] [,2] [,3] [,4]
 [1,]    1   51  101  151
 [2,]    2   52  102  152
 [3,]    6   56  106  156
 [4,]    7   57  107  157
 [5,]   11   61  111  161
 [6,]   12   62  112  162
 [7,]   16   66  116  166
 [8,]   17   67  117  167
 [9,]   21   71  121  171
[10,]   22   72  122  172
[11,]   26   76  126  176
[12,]   27   77  127  177
[13,]   31   81  131  181
[14,]   32   82  132  182
[15,]   36   86  136  186
[16,]   37   87  137  187
[17,]   41   91  141  191
[18,]   42   92  142  192
[19,]   46   96  146  196
[20,]   47   97  147  197

Maybe you want this:

simple[seq_len(nrow(simple)) %% 3 != 0,]

Output:

     [,1] [,2] [,3] [,4]
 [1,]    1   51  101  151
 [2,]    2   52  102  152
 [3,]    4   54  104  154
 [4,]    5   55  105  155
 [5,]    7   57  107  157
 [6,]    8   58  108  158
 [7,]   10   60  110  160
 [8,]   11   61  111  161
 [9,]   13   63  113  163
[10,]   14   64  114  164
[11,]   16   66  116  166
[12,]   17   67  117  167
[13,]   19   69  119  169
[14,]   20   70  120  170
[15,]   22   72  122  172
[16,]   23   73  123  173
[17,]   25   75  125  175
[18,]   26   76  126  176
[19,]   28   78  128  178
[20,]   29   79  129  179
[21,]   31   81  131  181
[22,]   32   82  132  182
[23,]   34   84  134  184
[24,]   35   85  135  185
[25,]   37   87  137  187
[26,]   38   88  138  188
[27,]   40   90  140  190
[28,]   41   91  141  191
[29,]   43   93  143  193
[30,]   44   94  144  194
[31,]   46   96  146  196
[32,]   47   97  147  197
[33,]   49   99  149  199
[34,]   50  100  150  200
  • Related