Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:在每列中选择不同的行_R_Performance_Subset - Fatal编程技术网

R:在每列中选择不同的行

R:在每列中选择不同的行,r,performance,subset,R,Performance,Subset,我有一个矩阵: x = rbind(1:5, 6:10) x [,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 6 7 8 9 10 我想根据索引为每列选择不同的行。例如,我可能想得到一个新的向量 [1] 1 2 8 4 10 在适当的列中选择行c(1,1,2,1,2)。我可以这样做: diag(x[c(1,1,2,1,2),]) [1] 1 2 8 4 10 但这

我有一个矩阵:

x = rbind(1:5, 6:10)
x
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    6    7    8    9   10 
我想根据索引为每列选择不同的行。例如,我可能想得到一个新的向量

[1]  1  2  8  4 10
在适当的列中选择行
c(1,1,2,1,2)
。我可以这样做:

diag(x[c(1,1,2,1,2),])
[1]  1  2  8  4 10
但这是内存效率低下的原因,因为它创建了以下矩阵:

x[c(1,1,2,1,2),]
    [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    6    7    8    9   10
[4,]    1    2    3    4    5
[5,]    6    7    8    9   10

给定一个真实的数据集和多次迭代,我担心一个严重的性能问题。如何根据索引有效地提取相同的值?

我们可以使用
行/列
索引

 x[cbind(c(1,1,2,1,2), 1:ncol(x))]
 #[1]  1  2  8  4 10

有趣。以前从来都不知道这是可能的。