abhishek dandona abhishek dandona - 3 months ago 14
R Question

Interpretation of the following R code

The query is to select elements at indices 1,4,7,10,13...

It could be done in several ways, but I do not understand the working of the following :

yVec <- sample(0:999,size = 250,replace = T)
yVec[c(T,F,F)]


Output:
[1] 709 517 437 783 671 860 581 347 279 974 216 776 538 460 985 248 317 288 687 957 938 101
[23] 615 285 106 414 881 488 484 791 246 643 845 553 465 87 993 116 473 635 310 428 965 19
[45] 489 803 604 800 175 516 902 689 881 593 835 398 358 850 791 915 665 167 866 942 320 482
[67] 216 488 681 273 884 970 469 717 127 952 284 695 325 777 792 72 738 791

Answer

The vector c(TRUE, FALSE, FALSE) is recycling to the entire vector and will extract the 1st, 4th, 7th, etc values of the vector. It is similar to replicating the logical vector to the length of the vector.

yVec[rep(c(TRUE, FALSE, FALSE), length.out = length(yVec))]

Wherever the logical vector is TRUE, it will extract the corresponding element in 'yVec'.