2

I have a list of elements where the number of elements is not fixed. I would like to name the element automatically based on their number. For example, if the list contains 9, then I would like to give names for the nine elements, as Model_1, Model_2, and so on. If the number of the element is changed, then, I do not need to change it manually.

For example, in the following code, the name of the elements must be done manually.

names1 <- c("1","2", "3", "4", "5", "6", "7", "8", "9")

lapply(setNames(unlist(myres), paste0(names1, '_Model')), function(x) 
  setNames(x, paste0('Res_', seq_along(x))))

Is there an automatic way to set the names of the elements which are not fixed?

  • 1
    It's not clear to me what you're input and what's your desired output, but if your list is `myres`, then you can do `setNames(myres, paste0("Model_", seq_along(myres))`. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 06 '21 at 06:40

2 Answers2

1

Something like this?

names(myres) <- paste0("Model_", 1:length(myres))

or

setNames(myres, paste0("Model_", 1:length(myres)))
Manuel Popp
  • 1,003
  • 1
  • 10
  • 33
0
library(purrr)
the_list <- map(1:5, ~.x)

names <- paste0('result', as.character(seq(1, length(the_list))))
purrr::set_names(the_list, names)
#> $result1
#> [1] 1
#> 
#> $result2
#> [1] 2
#> 
#> $result3
#> [1] 3
#> 
#> $result4
#> [1] 4
#> 
#> $result5
#> [1] 5

more_names <- 
    map(1:5, ~ rep(1, .x)) %>% 
    map(~length(.x)) %>% 
    map(~paste0('result', as.character(seq(1, .x))) )


map(1:5, ~ vector('list', .x)) %>% 
    map2(more_names, ~ set_names(.x, .y))
#> [[1]]
#> [[1]]$result1
#> NULL
#> 
#> 
#> [[2]]
#> [[2]]$result1
#> NULL
#> 
#> [[2]]$result2
#> NULL
#> 
#> 
#> [[3]]
#> [[3]]$result1
#> NULL
#> 
#> [[3]]$result2
#> NULL
#> 
#> [[3]]$result3
#> NULL
#> 
#> 
#> [[4]]
#> [[4]]$result1
#> NULL
#> 
#> [[4]]$result2
#> NULL
#> 
#> [[4]]$result3
#> NULL
#> 
#> [[4]]$result4
#> NULL
#> 
#> 
#> [[5]]
#> [[5]]$result1
#> NULL
#> 
#> [[5]]$result2
#> NULL
#> 
#> [[5]]$result3
#> NULL
#> 
#> [[5]]$result4
#> NULL
#> 
#> [[5]]$result5
#> NULL

Created on 2021-06-06 by the reprex package (v2.0.0)

jpdugo17
  • 6,816
  • 2
  • 11
  • 23