Search code examples
rlistvectorsubtraction

Subtract vector from list


How to perform such operation:

a <- list(b=1, c=c(2,3))
d <- c(1,1,2)
e <- list(b=0, c=c(1,1))

I am trying to subtract: a - d = e. But in theory we cannot subtract vector from list and get list with the same structure. Could anyone help me, please?


Solution

  • You can combine relist and unlist:

    > relist(unlist(a) - d, a)
    
    $b
    [1] 0
    
    $c
    [1] 1 1