Reputation: 574
I have a lists of list in r. I want to find maximum values for each row in each list.
Here is my data:
$`01-2020`
$`01-2020`$h1
[1] 5 5 5 1 6 1 6 4 4 2
$`01-2020`$h2
[1] 5 1 7 0 8
$`02-2020`
$`02-2020`$h1
[1] 0 0 0 0 1 2 1 1 1
$`02-2020`$h2
[1] 10 8 7 5 4
and its structure:
data<-list(`01-2020` = list(h1 = c(5, 5, 5, 1, 6, 1, 6, 4, 4, 2), h2 = c(5,
1, 7, 0, 8)), `02-2020` = list(h1 = c(0, 0, 0, 0, 1, 2, 1, 1,
1), h2 = c(10, 8, 7, 5, 4)))
I want to obtain these output values:
$`01-2020`
$`01-2020`$h1
[1] 6
$`01-2020`$h2
[1] 8
$`02-2020`
$`02-2020`$h1
[1] 2
$`02-2020`$h2
[1] 10
And also I see outputs like this:
But what I want to see is like the example below. I mean, without blue down arrow. also like double[2x1]
, not separate double[1]
rows :
Upvotes: 1
Views: 284
Reputation: 887851
We can use rrapply
library(rrapply)
rrapply(data, f = max)
-output
#$`01-2020`
#$`01-2020`$h1
#[1] 6
#$`01-2020`$h2
#[1] 8
#$`02-2020`
#$`02-2020`$h1
#[1] 2
#$`02-2020`$h2
#[1] 10
Or as @27 ϕ 9
suggested in the comments, a base R
alternative is rapply
rapply(data, max, how = "list")
Or another option is a nested lapply
from base R
lapply(data, function(x) lapply(x, max))
Or to get the structure correctly
out <- lapply(data, function(x) unname(sapply(x, max)))
Upvotes: 5