I have an arbitrary data frame, let's say it is of 360 rows which comprises 5 groups, each has 72 rows:
tally <- list(rows = 72, groups = 5)
I want to create a sequence of indexes following this pattern:
1 72 * 0, 1 72 * 1, 1 72 * 2, 1 72 * 3, 1 72 * 4
2 72 * 0, 2 72 * 1, 2 72 * 2, 2 72 * 3, 2 72 * 4
......
71 72 * 0, 1 72 * 1, 1 72 * 2, 1 72 * 3, 1 72 * 4
72 72 * 0, 1 72 * 1, 1 72 * 2, 1 72 * 3, 1 72 * 4
The sequence will be:
1, 73, 145, 217, 289,
2, 74, 146. 218, 290,
......
71, 143, 215, 287, 359,
72, 144, 216, 289, 360
Seems that function seq()
doesn't accept vector like this:
seq(from = seq_len(tally$rows), to = tally$rows * tally$rows, by = tally$rows)
So I wrote a function to generate the sequence:
create_indexes_by_group <- function(tally = NULL) {
bases <- seq_len(tally$rows)
indexes_list <- lapply(bases, FUN = function(x) {seq(from = x, to = tally$groups * tally$rows, by = tally$rows)})
return(unlist(indexes_list))
}
Is there a shorter way to create the sequence, maybe without introducing dependencies?
CodePudding user response:
We could use rep
with seq
out <- with(tally, rep(sequence(rows), each = groups)
(rep(rows, each = groups) * (seq(groups) -1)))
-output
out
[1] 1 73 145 217 289 2 74 146 218 290 3 75 147 219 291 4 76 148 220 292 5 77 149 221 293 6 78 150 222 294 7 79 151 223 295 8 80 152
[39] 224 296 9 81 153 225 297 10 82 154 226 298 11 83 155 227 299 12 84 156 228 300 13 85 157 229 301 14 86 158 230 302 15 87 159 231 303 16
[77] 88 160 232 304 17 89 161 233 305 18 90 162 234 306 19 91 163 235 307 20 92 164 236 308 21 93 165 237 309 22 94 166 238 310 23 95 167 239
[115] 311 24 96 168 240 312 25 97 169 241 313 26 98 170 242 314 27 99 171 243 315 28 100 172 244 316 29 101 173 245 317 30 102 174 246 318 31 103
[153] 175 247 319 32 104 176 248 320 33 105 177 249 321 34 106 178 250 322 35 107 179 251 323 36 108 180 252 324 37 109 181 253 325 38 110 182 254 326
[191] 39 111 183 255 327 40 112 184 256 328 41 113 185 257 329 42 114 186 258 330 43 115 187 259 331 44 116 188 260 332 45 117 189 261 333 46 118 190
[229] 262 334 47 119 191 263 335 48 120 192 264 336 49 121 193 265 337 50 122 194 266 338 51 123 195 267 339 52 124 196 268 340 53 125 197 269 341 54
[267] 126 198 270 342 55 127 199 271 343 56 128 200 272 344 57 129 201 273 345 58 130 202 274 346 59 131 203 275 347 60 132 204 276 348 61 133 205 277
[305] 349 62 134 206 278 350 63 135 207 279 351 64 136 208 280 352 65 137 209 281 353 66 138 210 282 354 67 139 211 283 355 68 140 212 284 356 69 141
[343] 213 285 357 70 142 214 286 358 71 143 215 287 359 72 144 216 288 360