Search code examples
rlistnullreplicate

R How to replicate nulls in a list


list(list(NULL,NULL),list(NULL,NULL))

The result is:

[[1]]
[[1]][[1]]
NULL

[[1]][[2]]
NULL

[[2]]
[[2]][[1]]
NULL

[[2]][[2]]
NULL

Supposing I want to do this for larger numbers than 2, is there a way to get the same list structure with replicate?


Solution

  • Use replicate

    replicate(n=3, {replicate(n=3,NULL,simplify=FALSE)},simplify=FALSE)
    
    
    [[1]]
    [[1]][[1]]
    NULL
    
    [[1]][[2]]
    NULL
    
    [[1]][[3]]
    NULL
    
    
    [[2]]
    [[2]][[1]]
    NULL
    
    [[2]][[2]]
    NULL
    
    [[2]][[3]]
    NULL
    
    
    [[3]]
    [[3]][[1]]
    NULL
    
    [[3]][[2]]
    NULL
    
    [[3]][[3]]
    NULL
    

    Or more simplly (thanks @RichardScriven)

    replicate(3, list(replicate(3, list(NULL))))