how to create a list in R from two vectors (one would be the keys, the other the values)?

前端 未结 5 1134
离开以前
离开以前 2020-12-29 23:03

I have two vectors and I want to create a list in R where one vector are the keys and the other the values. I thought that I was going to find easily the answer in my books

5条回答
  •  情话喂你
    2020-12-29 23:26

    It can be done in one statement using setNames:

    xx <- 1:3
    yy <- letters[1:3]
    

    To create a named list:

    as.list(setNames(xx, yy))
    # $a
    # [1] 1
    # 
    # $b
    # [1] 2
    # 
    # $c
    # [1] 3
    

    Or a named vector:

    setNames(xx, yy)
    # a b c 
    # 1 2 3
    

    In the case of the list, this is programmatically equivalent to your "named vector" approach but maybe a little more elegant.


    Here are some benchmarks that show the two approaches are just as fast. Also note that the order of operations is very important in avoiding an unnecessary and costly copy of the data:

    f1 <- function(xx, yy) {
      names(xx) <- yy
      as.list(xx)
    }
    
    f2 <- function(xx, yy) {
      out <- as.list(xx)
      names(out) <- yy
      out
    }
    
    f3 <- function(xx, yy) as.list(setNames(xx, yy))
    f4 <- function(xx, yy) setNames(as.list(xx), yy)
    
    library(microbenchmark)
    microbenchmark(
      f1(xx, yy),
      f2(xx, yy),
      f3(xx, yy),
      f4(xx, yy)
    )
    # Unit: microseconds
    #        expr    min      lq  median      uq     max neval
    #  f1(xx, yy) 41.207 42.6390 43.2885 45.7340 114.853   100
    #  f2(xx, yy) 39.187 40.3525 41.5330 43.7435 107.130   100
    #  f3(xx, yy) 39.280 41.2900 42.1450 43.8085 109.017   100
    #  f4(xx, yy) 76.278 78.1340 79.1450 80.7525 180.825   100
    

提交回复
热议问题