Convert vector to list

I have such a vector

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

and I would like to create this list

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

Is there any way to do this in an "apply" style? Thanks.

-k

+7
r
source share
4 answers

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 pleasure to Gavin to determine the early mistake.

+7
source share

Using as.list and setNames :

 x = c("1", "a","b") as.list(setNames(rep(as.numeric(x[1]), length(x) - 1), x[-1])) 
+10
source share

This is not an application style, but a simple function to transfer the necessary commands:

 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 
+5
source share

For completeness, a simpler, single-line liner is executed in the "apply" style as requested:

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

Although this is not the fastest option, it is certainly neat enough to earn its place as an answer to a question. Significant acceleration is possible without unnecessarily simplifying the 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 
+2
source share

All Articles