brucezepplin
brucezepplin

Reputation: 9792

preserve list elements as names in lapply function

Say I have the following:

seq<-c(2,3,4)
added<-lapply(1:length(seq),function(i){
       seq[i]+1
       }
)

> added
[[1]]
[1] 3

[[2]]
[1] 4

[[3]]
[1] 5

How do I use the list elements in seq to name the list elements of 'added'?

i.e.

> added
  [[2]]
  [1] 3

  [[3]]
  [1] 4

  [[4]]
  [1] 5

thank you

ACCEPTED SOLUTION from @akrun

seq<-c(2,3,4)
added<-setNames(lapply(1:length(seq),function(i){
seq[i]+1
}
),seq1)

Upvotes: 1

Views: 1514

Answers (2)

Nettle
Nettle

Reputation: 3321

library(purrr) seq<-c(2,3,4) set_names(seq, seq_along(seq))

or

seq %>% set_names(seq_along(.))

Upvotes: 0

akrun
akrun

Reputation: 887951

You could try

 added <- setNames(added, seq)

Or

 names(added) <- seq

Upvotes: 3

Related Questions