Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.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 - Fatal编程技术网

R 矩阵中行的最大值

R 矩阵中行的最大值,r,R,我有一个矩阵,在R中包含三列。该矩阵可以如下所示: A=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3) B=matrix(c(0,0,0,1,0,0,1,0,1,1,0,0),nrow=4,ncol=3) 我想创建一个基于a的矩阵,在a的每一行中,该行的最高值返回1,否则返回0。在上面的具体案例中,我需要一个如下所示的矩阵: A=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3

我有一个矩阵,在R中包含三列。该矩阵可以如下所示:

A=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3)
B=matrix(c(0,0,0,1,0,0,1,0,1,1,0,0),nrow=4,ncol=3)
我想创建一个基于a的矩阵,在a的每一行中,该行的最高值返回1,否则返回0。在上面的具体案例中,我需要一个如下所示的矩阵:

A=matrix(c(1,2,3,4,0.5,1,7,1.2,3,4,2,1),nrow=4, ncol=3)
B=matrix(c(0,0,0,1,0,0,1,0,1,1,0,0),nrow=4,ncol=3)
我试图搜索论坛,但找不到合适的答案


谢谢。

也许是这样的

t(apply(A, 1, function(x) as.numeric(x == max(x))))
#      [,1] [,2] [,3]
# [1,]    0    0    1
# [2,]    0    0    1
# [3,]    0    1    0
# [4,]    1    0    0

请注意,如果一行中有多个值与最大值匹配,则每行可能有多个“1”。

下面的内容与Ananda的答案基本相同,但如果a足够大,则微小的更改可能会对速度产生影响

> A<-matrix(rnorm(1000*1000),nrow=1000)
> system.time(t(apply(A, 1, function(x) as.numeric(x == max(x)))))
   user  system elapsed
  0.117   0.024   0.141
> system.time(1*(A==apply(A,1,max)))
   user  system elapsed
  0.056   0.008   0.065
>一个系统时间(t(应用(A,1,函数(x)为.numeric(x==max(xЮ)'))
用户系统运行时间
0.117   0.024   0.141
>系统时间(1*(A==apply(A,1,max)))
用户系统运行时间
0.056   0.008   0.065

表格(1:nrow(A),apply(A,1,which.max))
@rawr,不错!看起来在速度和牙链上是相当的,这就行了。