通过在 R 中的矩阵中选择具有特定值的位置对矩阵进行子采样

Subsample a matrix by selection locations with specific values within a matrix in R

我必须使用 R 而不是 Matlab,而且我是新手。

我有大量重复的数据,例如 1、2、3、4、5、6、7、8、9、10、1、2、3、4、5、6、7、8, 9、10...

我需要找到值等于 1、4、7、10 的位置,以使用这些位置创建样本。

此时就是position(=对应值) 1(=1) 4(=4) 7(=7) 10(=10) 11(=1) 14(=4) 17(= 7) 20(=10) 等等。

在 MatLab 中是 y=find(ismember(x,[1, 4, 7, 10 ])), 请帮忙!谢谢,帕维尔

是这样的吗?

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,请随意复制我的答案并获得对您答案的认可,只需尝试关闭已回答的问题。

%in% 运算符就是您想要的。例如,

# 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]

如果您想要位置的行索引和列索引,将需要一两个额外的步骤,但不清楚您是否这样做。 (注意,逻辑将按列顺序排列)。