Although I know how to do this in Python and Java, not that familiar with how to achieve this in R Especially I know R is very slow in loop and dynamically grow a list is slow.
assume I have a vector(list) a<-c(1,3,4), I want to have a list b that consists of elements from the following rule, any element k from a, include 3*k-2:3*k
in the list b.
e.g,
1 => 1,2,3
3 => 7,8,9
4 => 10,11,12
so b <- c(1,2,3,7,8,9,10,11,12)
now more generally, if I have a rule(function) f(k), how to append the return to the new list?
thanks
You want something like:
> unlist(lapply(c(1,3,4), function(k) (3*k-2):(3*k)))
[1] 1 2 3 7 8 9 10 11 12
But I don't follow your request for a more general solution.
Here's another way, for variety.
as.vector(mapply(`:`, 3*a-2, 3*a))
# [1] 1 2 3 7 8 9 10 11 12
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.