Home > Mobile >  In R name elements of a list with the same name followed by indeces
In R name elements of a list with the same name followed by indeces

Time:08-29

How can I name elements of a list with the same name followed by indeces (without the `-sign).

list1 <- c(1:5)
list2 <- c(1:5)

listall <- list(list1, list2)

names(listall) <- paste(rep("list", length(listall)), "[[", 1:length(listall), "]]", sep="")

listall

However this comes with the names being within

$`list[[1]]`
[1] 1 2 3 4 5

$`list[[2]]`
[1] 1 2 3 4 5

This is how I would like it to be:

$list[[1]]
[1] 1 2 3 4 5

$list[[2]]
[1] 1 2 3 4 5

CodePudding user response:

If the idea is to create list(list1 = 1:5, list2 = 1:5) using list1 and list2 as inputs without repeating them, i.e. without writing list(list1 = list1, list2 = list2), then here are some alternatives.

# 1 - this uses "list1" and "list2" but maybe it is close enough
mget(c("list1", "list2"))

# 2
# this one only works if the components are vectors of same length
# but they are in the question
as.list(data.frame(list1, list2))

# 3
library(tibble)
lst(list1, list2)

If what you meant was that you have a list list(list1, list2) and you just want to set the names of the two components to "list[[1]]" and "list[[2]]" then

  list1 <- list2 <- 1:5
  L <- list(list1, list2)
  nms <- sprintf("list[[%d]]", seq_along(L))
  names(L) <- nms

or use setNames in place of the last line producing a new list which is the same as L except for the names.

 setNames(L, nms)

If the list is displayed each name will be surrounded by back quotes because of the special characters in the names but those are not part of the names themselves -- they are just rendered that way.

If the square brackets are omitted it will not render them with back quotes.

nms <- sprintf("list%d", seq_along(L))
names(L) <- nms

CodePudding user response:

tldr; Names of list elements that contain special characters are not syntactically valid names. Backticks are used to refer to syntactically invalid names.


As per ?make.names:

A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number.

Backticks are a way to refer to names that are illegal, i.e. not syntactically valid. This is explained in some detail in e.g. ?Quotes.

In your case, you are trying to assign syntactically invalid names to the elements of a list. This is possible (though not advised) and results in the names being shown using backticks.

The only way to avoid the backticks is to use syntactically valid names.

  •  Tags:  
  • r
  • Related