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

前端 未结 3 1045
谎友^
谎友^ 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.

提交回复
热议问题