Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

I would like to create a vector in which each element is the i+6th element of another vector.

For example, in a vector of length 120, I want to create another vector of length 20 in which each element is value i, i+6, i+12, i+18... of the initial vector, i.e. I want to extract every 6th element of the original.

1 Answer

0 votes
by
edited by

To extract every nth element of a vector, you can do the following:

To create the vector:

 vec1 <- 1:120

> a

  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21

 [22]  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42

 [43]  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63

 [64]  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84

 [85]  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105

[106] 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

To extract the vector with nth element:

vec2 <- a[seq(1, length(a), 6)]

vec2

 [1]   1   7  13  19  25  31  37  43  49  55  61  67  73  79  85  91  97 103 109 115

Browse Categories

...