Search code examples
rlistrjsondata.tree

R: manipulate the list name


Here is my minimal reproducible example:

temp = list()
temp$rows$`1`$rows$name <- "rows"
temp$rows$`1`$rows$`1`$cells$name <- "cells"
temp$rows$`2`$rows$name <- "rows"
temp$rows$`2`$rows$`2`$cells$name <- "cells"

Current output:

$rows
$rows$`1`
$rows$`1`$rows
$rows$`1`$rows$name
[1] "rows"

$rows$`1`$rows$`1`
$rows$`1`$rows$`1`$cells
$rows$`1`$rows$`1`$cells$name
[1] "cells"





$rows$`2`
$rows$`2`$rows
$rows$`2`$rows$name
[1] "rows"

$rows$`2`$rows$`2`
$rows$`2`$rows$`2`$cells
$rows$`2`$rows$`2`$cells$name
[1] "cells"

I wonder is there a programmatic way to replace $1 to [[1]] and $2 to [[2]] in this list? So make the output look like this because this is an important step to make arrays when convert a list to JSON.

$rows
$rows[[1]]
$rows[[1]]$rows
$rows[[1]]$rows$name
[1] "rows"

$rows[[1]]$rows[[1]]
$rows[[1]]$rows[[1]]$cells
$rows[[1]]$rows[[1]]$cells$name
[1] "cells"





$rows[[2]]
$rows[[2]]$rows
$rows[[2]]$rows$name
[1] "rows"

$rows[[2]]$rows[[2]]
$rows[[2]]$rows[[2]]$cells
$rows[[2]]$rows[[2]]$cells$name
[1] "cells"

Here is what I tried but not working in the right way: lapply(temp$rows$1, unname)

Thanks!


Solution

  • This does what you want I think?

    First there's a function that renames any list elements with names "1" or "2" to be empty strings.

    The second function is recursive and goes through the nested list applying the first function to each element.

    fixnames <- function(x){
      names(x)[names(x)==1] <- ""
      names(x)[names(x)==2] <- ""
      x
      }
    
    rename <- function(x) {
        if(is.list(x)) lapply(fixnames(x), rename) else x
        }
    
    
    > rename(temp)
    $rows
    $rows[[1]]
    $rows[[1]]$rows
    $rows[[1]]$rows$name
    [1] "rows"
    
    $rows[[1]]$rows[[2]]
    $rows[[1]]$rows[[2]]$cells
    $rows[[1]]$rows[[2]]$cells$name
    [1] "cells"
    
    
    
    
    
    $rows[[2]]
    $rows[[2]]$rows
    $rows[[2]]$rows$name
    [1] "rows"
    
    $rows[[2]]$rows[[2]]
    $rows[[2]]$rows[[2]]$cells
    $rows[[2]]$rows[[2]]$cells$name
    [1] "cells"