仅将apply()应用于深度嵌入的列表元素

时间:2010-05-21 10:46:09

标签: list r apply

我想将我的函数仅应用于列表结构中更深层的元素。

例如,我想应用某个函数来仅列出二阶元素。这是可行的apply()?

> str(l)
List of 3
 $ :List of 2
  ..$ : num 5
  ..$ : num 10
 $ :List of 2
  ..$ : num 15
  ..$ : num 20
 $ :List of 2
  ..$ : num 25
  ..$ : num 30

2 个答案:

答案 0 :(得分:2)

使用双lapply

L <- list(
    list(rnorm(10),rnorm(10)),
    list(c(rnorm(10),NA),rnorm(10)),
    list(rnorm(10),rnorm(10))
    )
str(L)

L_out <- lapply(L, lapply, function(x) c(max(x),mean(x), mean(x,na.rm=TRUE)))
str(L_out)
# List of 3
#  $ :List of 2
#   ..$ : num [1:3] 0.958 0.127 0.127
#   ..$ : num [1:3] 0.981 -0.262 -0.262
#  $ :List of 2
#   ..$ : num [1:3] NA NA -0.443
#   ..$ : num [1:3] 1.126 -0.504 -0.504
#  $ :List of 2
#   ..$ : num [1:3] 1.432 -0.174 -0.174
#   ..$ : num [1:3] 1.102 -0.311 -0.311

答案 1 :(得分:-1)

不知道“r”,但我确信您可以应用适用于您的功能的功能。 让你的功能为f,然后应用f write apply(apply f)

在haskell-ish

data = [[5,10], [15,20], [25,3]]

假设我们想为每个数字添加1:

map (map (+1)) data