我在 r 中有一个列表列表。我想为每个列表中的每一行找到最大值。
这是我的数据:
$`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
Run Code Online (Sandbox Code Playgroud)
及其结构:
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)))
Run Code Online (Sandbox Code Playgroud)
我想获得这些输出值:
$`01-2020`
$`01-2020`$h1
[1] 6
$`01-2020`$h2
[1] 8
$`02-2020`
$`02-2020`$h1
[1] 2
$`02-2020`$h2
[1] 10
Run Code Online (Sandbox Code Playgroud)
但我想看到的就像下面的例子。我的意思是,没有蓝色向下箭头。也喜欢double[2x1],而不是单独的double[1]行:

我们可以用 rrapply
library(rrapply)
rrapply(data, f = max)
Run Code Online (Sandbox Code Playgroud)
-输出
#$`01-2020`
#$`01-2020`$h1
#[1] 6
#$`01-2020`$h2
#[1] 8
#$`02-2020`
#$`02-2020`$h1
#[1] 2
#$`02-2020`$h2
#[1] 10
Run Code Online (Sandbox Code Playgroud)
或者按照@27 ? 9评论中的建议,base R另一种选择是rapply
rapply(data, max, how = "list")
Run Code Online (Sandbox Code Playgroud)
或者另一个选项是嵌套lapply从base R
lapply(data, function(x) lapply(x, max))
Run Code Online (Sandbox Code Playgroud)
或者正确获取结构
out <- lapply(data, function(x) unname(sapply(x, max)))
Run Code Online (Sandbox Code Playgroud)