Creating a named list from two vectors (names, values)

前端 未结 3 1032
谎友^
谎友^ 2020-12-24 04:54

Is there a way to use mapply on two vectors to construct a named list? The first vector would be of type character and contain the names used for the list while

相关标签:
3条回答
  • 2020-12-24 05:32

    I share Ben's puzzlement about why you might want to do this, and his recommendation.

    Just for curiosity's sake, there is a sort of "hidden" feature in mapply that will allow this:

    x <- letters[1:2]
    y <- 1:2
    mapply(function(x,y) { y }, x, y, SIMPLIFY = FALSE,USE.NAMES = TRUE)
    $a
    [1] 1
    
    $b
    [1] 2
    

    Noting that the documentation for USE.NAMES says:

    USE.NAMES logical; use names if the first ... argument has names, or if it is a character vector, use that character vector as the names.

    0 讨论(0)
  • 2020-12-24 05:41

    What I propose is made in 2 steps, and it's quite straightforward, so maybe it's easier to understand:

    test_list <- list(1, 2)
    names(test_list) <- c("foo", "bar")
    

    What @ben-bolker proposes works, but just wanted to share an alternative, in case you prefer it.

    Happy coding!

    0 讨论(0)
  • 2020-12-24 05:51

    You can use setNames()

    setNames(as.list(c(1, 2)), c("foo", "bar"))
    

    (for a list) or

    setNames(c(1, 2), c("foo", "bar"))
    

    (for a vector)

    0 讨论(0)
提交回复
热议问题