0

I want to assign char value from variable to use name in named list.

n <- "EDF04"
l1 <- list(n = c(1,2,3))
Result:
$c
[1] 1 2 3

Expected Result:
$EDF04
[1] 1 2 3

1
  • 1
    names(l1) <- n Commented Jul 31, 2020 at 15:52

1 Answer 1

0

Are you just looking for names<- ?

n  <- "EDF04"
l1 <- list(n = c(1,2,3))
names(l1) <- n
l1
#> $EDF04
#> [1] 1 2 3

or setNames?

setNames(list(c(1,2,3)), n)
#> $EDF04
#> [1] 1 2 3

Or are you wanting to do something fancier?

mylist <- function(...) {
  mc <- as.list(match.call())[-1]
  par_names <- names(mc)
  li_names <- sapply(par_names, function(i){
    if(nzchar(i)) {
      a_name <- if(exists(i, envir = parent.frame()))
        get(i, envir = parent.frame()) else i
        if(length(a_name) == 1 & class(a_name) == "character") return(a_name)
    } else return("")
  })
  setNames(list(...), li_names)
}

mylist(n = 1, z = 4, c(5, 6, 7)) 
#> $EDF04
#> [1] 1
#> 
#> $z
#> [1] 4
#>
#> [[3]]
#> [1] 5 6 7

Created on 2020-07-31 by the reprex package (v0.3.0)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.