Refers to a nested list of data frames in R

I have a nested list, the fundamental element of which is data frames, and I want to cross this list recursively in order to do some calculation of each data frame, finally, to get a nested list of results in the same structure as the input. I know that β€œrapple” is just such a task, but I ran into a problem that, in fact, fits even deeper than I want, i.e. it decomposes each data frame and applies to each column (because the data frame itself is a list in R).

The workaround I can think of is to convert each frame of data into a matrix, but this will lead to a unification of data types, so I don't like it. I want to know if there is a way to control the recursive depth of the rapper. Any ideas? Thanks.

+4
source share
1 answer

1. wrap in proto

When creating a list structure, try wrapping data frames in proto-objects:

library(proto) L <- list(a = proto(DF = BOD), b = proto(DF = BOD)) rapply(L, f = function(.) colSums(.$DF), how = "replace") 

giving:

 $a Time demand 22 89 $b Time demand 22 89 

Wrap the result of your function in a proto-object, if you want more rapply it;

 f <- function(.) proto(result = colSums(.$DF)) out <- rapply(L, f = f, how = "replace") str(out) 

giving:

 List of 2 $ a:proto object .. $ result: Named num [1:2] 22 89 .. ..- attr(*, "names")= chr [1:2] "Time" "demand" $ b:proto object .. $ result: Named num [1:2] 22 89 .. ..- attr(*, "names")= chr [1:2] "Time" "demand" 

2. write your own alternative

 recurse <- function (L, f) { if (inherits(L, "data.frame")) f(L) else lapply(L, recurse, f) } L <- list(a = BOD, b = BOD) recurse(L, colSums) 

This gives:

 $a Time demand 22 89 $b Time demand 22 89 

ADDED: second approach

+5
source

Source: https://habr.com/ru/post/1494496/


All Articles