I have a vector like this
c(\"1\", \"a\",\"b\")
and I\'d like to create this list
list(\"a\"=1,\"b\"=1)
is
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