Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

by command to find out the maximum number from a list

Tags:

list

r

max

I have a list like this :

Ll 
$a
3.4 5.6 -2.1 -7.8
$b
2.1 6.7
$c
-6.7,0.001,8.9

I want to find out the maximum number for all elements of the list irrespective of the signs. i.e. I want my out put to look like this :

Ll
$a
-7.8
$b
6.7
$c
8.9

Is there a way to do this through single command line ? Can it be done using the 'by' command?

like image 959
user1021713 Avatar asked Jul 16 '12 04:07

user1021713


3 Answers

Reproducible code/data always helps:

L1 <- list(a = c(3.4, 5.6, -2.1, -7.8), b = c(2.1, 6.7), c = c(-6.7, 0.001, 8.9))

Use lapply to apply your own function to each element, which.max easily finds the maximum, and we just get the absolute value within each:

lapply(L1, function(x) x[which.max(abs(x))])
$a
[1] -7.8

$b
[1] 6.7

$c
[1] 8.9
like image 142
mdsumner Avatar answered Nov 20 '22 18:11

mdsumner


lapply is your friend!

eg.

.list <- list( a = 1:5, b = runif(7), c = -3:1)
 lapply(.list, function(x) x[which.max(abs(x))])
## $a
## [1] 5
## 
## $b
## [1] 0.9248526
## 
## $c
## [1] -3
like image 36
mnel Avatar answered Nov 20 '22 19:11

mnel


which.max will give you index number and value, however if you need just number that you can try this:

max(sapply(yourlist, max))

like image 32
Tymo Avatar answered Nov 20 '22 18:11

Tymo