convert a vector to a list

后端 未结 4 1076
爱一瞬间的悲伤
爱一瞬间的悲伤 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 17:04

    Like this?

    R> kn <- c("1", "a", "b")
    R> nl <- vector(mode="list", length=length(kn)-1)
    R> names(nl) <- kn[-1]
    R> nl <- lapply(nl, function(x) kn[1])
    R> nl
    $a
    [1] "1"
    
    $b
    [1] "1"
    
    R> 
    

    With kudos to Gavin for spotting an earlier error.

提交回复
热议问题