F F
F F

Reputation: 3

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.

Upvotes: 0

Views: 460

Answers (2)

George Savva
George Savva

Reputation: 5336

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

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101383

You can use Map like below

mylist[] <- Map(c, 0, mylist)

such that

> mylist
$a
[1] 0 1 2 3 4 5

$b
[1]  0 11 12 13 14 15

Upvotes: 2

Related Questions