[R] data manipulation

Gavin Simpson gavin.simpson at ucl.ac.uk
Fri Feb 29 16:41:35 CET 2008


On Fri, 2008-02-29 at 15:01 +0000, Luis Ridao Cruz wrote:
> R-help,
> 
> I have a data frame in which I compute maximum by rows
> and I wish to find out the column name at which this maximun occurs.
> 
> Does anyone know how to do it?
> 
> Thanks in advance

Do you mean compute the maximum value in a row and return which column
this maximum occurred in? If so this is one way:

> dat <- data.frame(matrix(rnorm(100), ncol = 5))
> names(dat) <- paste("Var", 1:5, sep = "")
> head(dat)
        Var1        Var2        Var3       Var4       Var5
1  0.1510373 -0.64807707 -1.01413243 -0.7456820  0.1048061
2 -2.6693159 -0.23994702  0.37635088  0.4827074 -0.4895318
3 -1.1881114  0.02976593 -2.30550629  0.8875579 -1.4371890
4 -0.2446966 -0.52986123  0.98211952  1.8524755  1.2228393
5  1.7373406 -0.94157744  2.07561600  0.9042968  0.1344427
6 -0.8973550 -1.48810446 -0.06583172  1.2900323  1.6134146
> apply(dat, 1, function(x) names(dat)[which.max(x)])
 [1] "Var1" "Var4" "Var4" "Var4" "Var3" "Var5" "Var1" "Var2" "Var5" "Var1"
[11] "Var2" "Var5" "Var1" "Var4" "Var1" "Var2" "Var1" "Var3" "Var4" "Var1"

Is that what you wanted?

if you want the column number, not the name, then replace the last line
with:

> apply(dat, 1, which.max)
 [1] 1 4 4 4 3 5 1 2 5 1 2 5 1 4 1 2 1 3 4 1

To combine these into a named vector:

> row.max <- apply(dat, 1, max)
> names(row.max) <- apply(dat, 1, function(x) names(dat)[which.max(x)])
> row.max
      Var1       Var4       Var4       Var4       Var3       Var5       Var1 
 0.1510373  0.4827074  0.8875579  1.8524755  2.0756160  1.6134146  1.0785170 
      Var2       Var5       Var1       Var2       Var5       Var1       Var4 
-0.1014373  1.7488679  0.2963419  0.3852797  1.0020775  0.8578898  0.8784652 
      Var1       Var2       Var1       Var3       Var4       Var1 
 0.5820790  2.0972333  1.2857461  0.7394983  0.4183199  0.9016516 

HTH

G

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list