如何从向量中提取数字的倍数 [英] How to extract multiples of a number from a vector
问题描述
我有一个向量让我们说
x <- 1:1000
我想从中提取 8 的倍数.
and I want to extract the multiples of 8 from it.
我该怎么办?(我不想做 x[-c(8,16,24,.....)]
)
What should I do?
(I don't want to do x[-c(8,16,24,.....)]
)
目标是从 x
向量中去除 8 的倍数.
The goal is to remove the multiples of 8 from the x
vector.
推荐答案
为此,您可以使用模运算符,即 %%
.举个例子:
For this you can use the modulo operator, i.e. %%
. Take for example:
> 322%%8
[1] 2
它告诉你 322 除以 8 后,剩下 2,即 320 正好是 8 的 40 倍,剩下 2.
which tells you that after dividing 322 by 8, 2 remains, i.e. 320 is exactly 40 times 8, leaving 2.
在你的例子中,我们可以使用 %%
结合子集来得到 8 的倍数.记住 %%
为 8 的精确倍数产生 0:>
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
还要注意 %%
是一个向量化操作,即左边是一个向量,结果也将是一个向量.multiple_of_8
向量现在包含 1000 个逻辑,说明 input
的特定元素是否是 8 的精确倍数.使用该逻辑向量进行子集化得到您需要的结果:>
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
或更紧凑:
input[(input %% 8) == 0]
这篇关于如何从向量中提取数字的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!