Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

r - How to extract multiples of a number from a vector

I have a vector let's say

x <- 1:1000

and I want to extract the multiples of 8 from it.

What should I do? (I don't want to do x[-c(8,16,24,.....)] )

The goal is to remove the multiples of 8 from the x vector.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For this you can use the modulo operator, i.e. %%. Take for example:

> 322%%8
[1] 2

which tells you that after dividing 322 by 8, 2 remains, i.e. 320 is exactly 40 times 8, leaving 2.

In you example we can use %% combined with subsetting to get the the multiples of 8. Remember that %% yields 0 for exact multiples of 8:

input = 1:1000
multiple_of_8 = (input %% 8) == 0
head(multiple_of_8)
[1] FALSE FALSE FALSE FALSE FALSE FALSE
length(multiple_of_8)
[1] 1000

also note that %% is a vectorized operation, i.e. of the left hand side is a vector, the result will also be a vector. The multiple_of_8 vector now contains 1000 logicals stating if that particular element of input is an exact multiple of 8. Using that logical vector to subset get's you the result you need:

input[multiple_of_8]
  [1]    8   16   24   32   40   48   56   64   72   80   88   96  104  112  120
 [16]  128  136  144  152  160  168  176  184  192  200  208  216  224  232  240
 [31]  248  256  264  272  280  288  296  304  312  320  328  336  344  352  360
 [46]  368  376  384  392  400  408  416  424  432  440  448  456  464  472  480
 [61]  488  496  504  512  520  528  536  544  552  560  568  576  584  592  600
 [76]  608  616  624  632  640  648  656  664  672  680  688  696  704  712  720
 [91]  728  736  744  752  760  768  776  784  792  800  808  816  824  832  840
[106]  848  856  864  872  880  888  896  904  912  920  928  936  944  952  960
[121]  968  976  984  992 1000

or more compactly:

input[(input %% 8) == 0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...