开发者

applying apply() to deeply embeded list elements only

开发者 https://www.devze.com 2022-12-30 22:36 出处:网络
I would like to apply my function to only element开发者_StackOverflows that are deeper in the list structure.

I would like to apply my function to only element开发者_StackOverflows that are deeper in the list structure.

For example, I would like to apply a certain function to list elements of second order only. Is this feasible with 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


Use double 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


Not knowing "r", but I am sure that you can apply a function that applies your function. Let your funktion be f, then instead apply f write apply (apply f)

In haskell-ish

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

Suppose we want to add 1 to each number:

map (map (+1)) data
0

精彩评论

暂无评论...
验证码 换一张
取 消