convert a vector to a list

后端 未结 4 1074
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    
    0 讨论(0)
  • 2021-02-15 16:59

    Using as.list and setNames:

    x = c("1", "a","b")
    as.list(setNames(rep(as.numeric(x[1]), length(x) - 1), x[-1]))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-15 17:08

    For completeness, there is a simpler one-liner to do it in an "apply" style as requested:

    as.list(sapply(x[-1],function(y) as.double(x[1])))
    

    While not the fastest option, it is surely neat enough to deserve its place as an answer to the question. A significant speed-up is possible by not unnecessarily simplifying to a vector:

        library(microbenchmark)
        microbenchmark(times=20, 
                   Charles=as.list(setNames(rep(as.numeric(x[1]), length(x) - 1), x[-1])),
                   Gavin=makeList(x),
                   Anon=sapply(x[-1],function(y) as.double(x[1]),simplify=FALSE)
    )
    
    Unit: microseconds
        expr    min      lq median      uq    max neval
     Charles 10.868 11.7735 11.774 12.3775 55.848    20
       Gavin 12.075 12.6795 13.132 13.8870 26.867    20
        Anon  6.643  7.0950  7.548  8.1520 17.811    20
    
    0 讨论(0)
提交回复
热议问题