rlistsapply

replace numeric(0) with 0 in R list


I have a list:

myList
$`0`
$`0`$item1
numeric(0)

$`0`$item2
[1] 350

$`0`$item3
numeric(0)


$`1`
$`1`$item1
numeric(0)

$`1`$item2
[1] 56

$`1`$item3
numeric(0)

I am using an sapply function on this list, but get an error:

invalid 'type' (list) of argument

how can i convert all numeric(0) to 0, like the other items?


Solution

  • In case the depth is not known or not equal you can use a recursive function:

    f <- function(x) {
      if(is.list(x)) lapply(x, f)
      else ifelse(length(x) == 0, 0, x)
    }
    
    f(myList)
    #$`0`
    #$`0`$item1
    #[1] 0
    #
    #$`0`$item2
    #[1] 350
    #
    #$`0`$item3
    #[1] 0
    #
    #
    #$`1`
    #$`1`$item1
    #[1] 0
    #
    #$`1`$item2
    #[1] 56
    #
    #$`1`$item3
    #[1] 0
    #
    #
    #$`2`
    #[1] 4
    #
    #$`3`
    #[1] 0
    

    Another option is to use rapply

    rapply(myList, \(x) {if(length(x)==0) 0 else x}, how="replace")
    

    Data:

    myList <- list(`0` = list(item1 = numeric(0), item2 = 350, item3 = numeric(0)),
                   `1` = list(item1 = numeric(0), item2 = 56, item3 = numeric(0)),
                   `2` = 4, `3` = numeric(0))