I have a vector like this
c(\"1\", \"a\",\"b\")
and I\'d like to create this list
list(\"a\"=1,\"b\"=1)
is
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
Using as.list
and setNames
:
x = c("1", "a","b")
as.list(setNames(rep(as.numeric(x[1]), length(x) - 1), x[-1]))
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.
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