Search code examples
rlistpositionelementaddition

How can I add a value to every object of a list at the first position in R


I wonder if there is a way to add a "0" to every element of a R-list at the first position.

mylist <- list (a = 1:5, b = 11:15)

I'm looking for an easy way that produces the following result:

mylist[[1]]

[1] 0 1 2 3 4 5

mylist[[2]]

[1] 0 11 12 13 14 15

Of course my list has much more objects than just two.


Solution

  • lapply takes a list as an argument, applies a function to each element and returns a list of the results

    lapply( mylist , function(x) c(0,x))
    
    $a
    [1] 0 1 2 3 4 5
    
    $b
    [1]  0 11 12 13 14 15