How to make an infinitely recursive list in R: confuse [ and [[ -
edit: question silly, confused [ , [[ (thanks @josilber), can't delete it.
how can 1 make infinitely recursive list, l == l[1], in r ?
terrible way (for r novice) @ dataset fmri
in package astsa:
data( fmri, package="astsa" ) # list fmri[1] == fmri[1][1] ... ?? print_recursive = function( x ){ # x x[1] x[1][1] ... while list for( j in 1:5 ){ cat( class(x), len(x), names(x), "\n" ) str(x) cat( "\n" ) x = x[1] # <-- wrong, should x[[1]] if( class(x) != "list" ) break } x } x = print_recursive( fmri )
the answer "how can 1 make infinitely recursive list, l == l[1], in r" is impossible, because need infinite amount of memory store list of infinite recursive depth.
that being said, can build recursive list of specified depth simple loop, @ each iteration creating new list stores old list 1 of elements:
l <- list() depth <- 50 (k in seq(depth-1)) { l <- list(l) }
you write recursive function check depth of recursive list:
recursive.depth <- function(l) { if (!is.list(l)) 0 else if (length(l) == 0) 1 else 1+max(sapply(l, recursive.depth)) } recursive.depth(l) # [1] 50 recursive.depth(fmri) # [1] 1
getting example question, list have not recursive @ (it's list of matrices). reason think recursive indexing l[1]
subsets list (aka returns list first element). instance, consider following simple list:
(l <- list(2)) # [[1]] # [1] 2
no matter how many times subset [
notation, exact same list:
l[1] # [[1]] # [1] 2 l[1][1] # [[1]] # [1] 2
running list l
through print_recursive
function result in infinite loop. if wanted extract first element of list instead of subsetting list itself, should use [[
notation (e.g. l[[1]]
).
Comments
Post a Comment