tags:

views:

72

answers:

2

I would like to apply my function to only elements 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
A: 

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
Ingo
+2  A: 

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
Marek
If there is a list in the 3rd level, I'm afraid you'll get an `invalid type of argument` error
gd047
@gd047 Yes, but it depends on function which you want to apply on sublists. For example if you had list of lists of list of data.frames, and you want rbind this data.frames then use `lapply(L, lapply, function(x) do.call(rbind,x)`. My solution is workaround when you have list of list instead of list.
Marek
That is cool...
Tal Galili