convert a vector to a list

后端 未结 4 1063
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 16:03

I have a vector like this

 c(\"1\", \"a\",\"b\")

and I\'d like to create this list

list(\"a\"=1,\"b\"=1)

is

4条回答
  •  我在风中等你
    2021-02-15 16:56

    It isn't an apply style, but a simple function to wrap the required commands is:

    makeList <- function(vec) {
        len <- length(vec[-1])
        out <- as.list(rep(as.numeric(vec[1]), len))
        names(out) <- as.character(vec[-1])
        out
    }
    

    Using your vector, it gives:

    > vec <- c("1", "a","b")
    > makeList(vec)
    $a
    [1] 1
    
    $b
    [1] 1
    

提交回复
热议问题