0

I'm have to use R instead of Matlab and I'm new to it.

I have a large array of data repeating like 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10...

I need to find the locations where values equal to 1, 4, 7, 10 are found to create a sample using those locations.

In this case it will be position(=corresponding value) 1(=1) 4(=4) 7(=7) 10(=10) 11(=1) 14(=4) 17(=7) 20(=10) and so on.

in MatLab it would be y=find(ismember(x,[1, 4, 7, 10 ])), Please, help! Thanks, Pavel

Porco
  • 195
  • 1
  • 4
  • 16

2 Answers2

0

something like this?

foo <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
bar <- c(1, 4, 7, 10)
which(foo %in% bar)
#> [1]  1  4  7 10 11 14 17 20

@nicola, feel free to copy my answer and get the recognition for your answer, simply trying to close answered questions.

Eric Fail
  • 8,191
  • 8
  • 72
  • 128
0

The %in% operator is what you want. For example,

# data in x
targets <- c(1, 4, 7, 10)
locations <- x %in% targets
# locations is a logical vector you can then use:
y <- x[locations]

There'll be an extra step or two if you wanted the row and column indices of the locations, but it's not clear if you do. (Note, the logicals will be in column order).

doctorG
  • 1,681
  • 1
  • 11
  • 27