-1

Data in RStudio Viewer

I got this matrix now, and I would like to find the min column and define:

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

(because the fifth column is the smallest).

What should I write to get y?

coatless
  • 20,011
  • 13
  • 69
  • 84
vicky2016
  • 1
  • 1
  • Welcome to StackOverflow! Please tell us what you have tried. Also, provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) to make it easier for us to help you - ie give us something we can copy-paste into R to reproduce your example. Have you searched for how to find a minimum, or the index of a minimum, in R? Have a look at `?which.min`. – mathematical.coffee Oct 11 '16 at 00:11
  • I guess you don't have a matrix there. You have some pseudocode for what a matrix looks like... With a matrix, I suppose you could do `as.integer(m == min(m))` to get a 0/1 matrix with ones at the min. – Frank Oct 11 '16 at 00:12
  • Would your matrix have only one row or is it a matrix where you would get multiple rows? If there are going to be multiple rows, would y also be a sparse matrix of the same size? – woodhead92 Oct 11 '16 at 00:14
  • Seems to be a duplicate of http://stackoverflow.com/questions/17551876/r-find-index-of-matrix-with-smallest-value – woodhead92 Oct 11 '16 at 00:15

2 Answers2

0

In this case, I believe you want 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
Michael Griffiths
  • 1,399
  • 7
  • 14
0

You can do it by using an ifelse statement.

> #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
Cris
  • 787
  • 1
  • 5
  • 19