John Smith John Smith - 3 months ago 9
R Question

Better R way of doing/replacing the following for loop

Just for educational reasons, is there an R better way (something with ?apply instead of the for loop) for the following? Been breaking my head but can't see the "solution".

foo_length <- 10
foo_list <- list("1"=c(1, 3, 4), "2"=c(2, 5, 9), "3"=c(6, 7, 8, 10))
foo <- rep(NA_integer_, foo_length)
for (iname in names(foo_list))
foo[foo_list[[iname]]] <- as.integer(iname)


Output of
foo
is
1 2 1 1 2 3 3 3 2 3

Answer

How about

lens <- sapply(foo_list,length)             ## lengths of components
foo <- numeric(foo_length)                  ## result vector (empty)
v <- rep(as.integer(names(foo_list)),lens)  ## matching vector
foo[unlist(foo_list)] <- v                  ## assign matching values

?