Home > Software engineering >  Is there a way to name all the elements of list
Is there a way to name all the elements of list

Time:12-16

Is there a way to name all the elements of list using names in array element_array.

element_names <- c("A", "B", "C", "D", "E")

x <- list()
for (iter in 1:5) {
  x[[iter]] <- seq(1, iter)
}

CodePudding user response:

You could do this more concise using Map and setNames.

x <- setNames(Map(seq, 1:5), element_names)
x
# $A
# [1] 1
# 
# $B
# [1] 1 2
# 
# $C
# [1] 1 2 3
# 
# $D
# [1] 1 2 3 4
# 
# $E
# [1] 1 2 3 4 5

Or, using the new pipe:

Map(seq, 1:5) |> setNames(element_names)

CodePudding user response:

Another way to generate a seq of list in R:

element_names <- LETTERS[1:5]
# initialise a list
x <- list()

# Loop through the length of list
for (i in seq(1,5)){
  vals <- seq(1, i)
  x[[element_names[i]]] <- vals
}
  •  Tags:  
  • r
  • Related