如何在这个矩阵中找到相应的列?

时间:2016-10-10 23:57:37

标签: r

Data in RStudio Viewer

我现在有了这个矩阵,我想找到min列并定义:

y = (0,0,0,0,1,0)

(因为第五列是最小的)。

我应该写什么才能获得y

2 个答案:

答案 0 :(得分:0)

在这种情况下,我相信你想要which.min

(sample.data <- matrix(rnorm(25), ncol = 5))
#>            [,1]       [,2]       [,3]        [,4]       [,5]
#> [1,]  1.7131439 -0.8245361  1.7140092 -1.05113511 0.08437935
#> [2,] -0.3139393 -0.1054446  1.5360771 -0.28580350 0.98912223
#> [3,]  0.8386972  0.6956972 -0.5144028  0.59367973 1.10062439
#> [4,]  0.1302335  1.4313643  1.3059922  0.48052815 1.83240308
#> [5,]  0.3926283 -0.5196746 -1.2081396  0.02681044 0.73020269

(mins <- apply(sample.data, 1, which.min))
#> [1] 4 1 3 1 3

答案 1 :(得分:0)

您可以使用ifelse语句来完成。

> #Generate DataFrame
> DF=data.frame(9.8,6,3.8,3.2,2.8,3)

  X9.8 X6 X3.8 X3.2 X2.8 X3
1  9.8  6  3.8  3.2  2.8  3

> #Put 1 to the lowest number and 0 to the rest
> ifelse(DF==min(DF),1,0)
     X9.8 X6 X3.8 X3.2 X2.8 X3
[1,]    0  0    0    0    1  0