简体   繁体   English

R由行号子集

[英]R Subset by row numbers

I have a large matrix “A” (14 columns but 250 000 rows). 我有一个大矩阵“ A”(14列但25万行)。 It has no id column. 它没有id列。

I have another matrix “B” (14x1) with 14 numbers. 我还有另一个带有14个数字的矩阵“ B”(14x1)。

1   1   3   7   15  31  63  127 255 511 1023    2047    4095    8191

I would like to subset “A” taking only the rows that have a number in B. Eg. 我想将仅包含B中具有数字的行的子集“ A”作为子集。 Row 1, 3, 7, 15, 31, etc. 第1、3、7、15、31行等

I have tried the following: 我尝试了以下方法:

newA <- A[nrow(A) %in% c(B),]

I didn't work. 我没工作 I have also tried to add an id column to the large matrix A (eg A$id <- 1:nrow(A) but it didn't work either. 我也试图将id列添加到大型矩阵A中(例如A$id <- 1:nrow(A)但它也不起作用)。

Try converting B to a numeric vector and use that to index A - this works with matrices regardless of how many rows and columns they have. 尝试将B转换为数值向量,然后将其用于索引A-不管矩阵有多少行和列,这都适用于矩阵。

B<-as.numeric(as.character(B))

newA<-A[B,]

Edit - refined for clarity and information on applicability to matrices of all dimensions. 编辑-进行了改进,以提高清晰度和有关适用于所有维度的矩阵的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM