24

假设我有以下向量:

x <- c(8, 6, 9, 9, 7, 3, 2, 5, 5, 1, 6, 8, 5, 2, 9, 3, 5, 10, 8, 2)

如何找到哪些元素是 8 或 9?

4

6 回答 6

40

这是一种方法。首先,我得到 x 为 8 或 9 的索引。然后我们可以验证在这些索引处,x 确实是 8 和 9。

> inds <- which(x %in% c(8,9))
> inds
[1]  1  3  4 12 15 19
> x[inds]
[1] 8 9 9 8 9 8
于 2009-07-23T03:13:38.963 回答
11

|您可以在短期条件下尝试运营商

which(x == 8 | x == 9)
于 2009-07-23T13:10:53.620 回答
2

这种特定情况下,您还可以使用grep

# option 1
grep('[89]',x)
# option 2
grep('8|9',x)

两者都给出:

[1]  1  3  4 12 15 19

When you also want to detect number with more than one digit, the second option is preferred:

> grep('10|8',x)
[1]  1 12 18 19

However, I did put emphasis on this specific case at the start of my answer for a reason. As @DavidArenburg mentioned, this could lead to unintended results. Using for example grep('1|8',x) will detect both 1 and 10:

> grep('1|8',x)
[1]  1 10 12 18 19

In order to avoid that side-effect, you will have to wrap the numbers to be detected in word-bounderies:

> grep('\\b1\\b|8',x)
[1]  1 10 12 19

Now, the 10 isn't detected.

于 2018-08-17T08:08:52.300 回答
2

Here is a generalized solution to find the locations of all target values (only works for vectors and 1-dimensional arrays).

locate <- function(x, targets) {
    results <- lapply(targets, function(target) which(x == target))
    names(results) <- targets
    results
}

This function returns a list because each target may have any number of matches, including zero. The list is sorted (and named) in the original order of the targets.

Here is an example in use:

sequence <- c(1:10, 1:10)

locate(sequence, c(2,9))
$`2`
[1]  2 12

$`9`
[1]  9 19
于 2020-02-19T21:45:00.157 回答
1

或者,如果您不需要使用索引而只需使用您可以执行的元素

> x <- sample(1:10,20,replace=TRUE)
> x
 [1]  6  4  7  2  9  3  3  5  4  7  2  1  4  9  1  6 10  4  3 10
> x[8<=x & x<=9]
[1] 9 9
于 2009-07-23T07:34:45.833 回答
-1

grepl也许是一个有用的功能。请注意,它grepl出现在 R 2.9.0 及更高版本中。方便的grepl是它返回一个与x.

grepl(8, x)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

grepl(9, x)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
[13] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE  TRUE

要得出您的答案,您可以执行以下操作

grepl(8,x) | grepl(9,x)
于 2009-07-26T18:26:30.800 回答