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

前端 未结 5 1119
离开以前
离开以前 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:27

    Do you mean to do this?...

    xx <- 1:3
    yy <- letters[1:3]
    zz <- list( xx , yy )
    names(zz) <- c("keys" , "values")
    zz
    #$keys
    #[1] 1 2 3
    
    #$values
    #[1] "a" "b" "c"
    

    AFAIK this is the canonical way of making a list of vectors. I am happy to be corrected. If you are new to R, I'd advise it is generally unwise to use a for loop because there are usually vectorised methods to accomplish most tasks that are more efficient and faster.

提交回复
热议问题