Jin
Jin

Reputation: 1223

efficient create a list based on another list in R

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

Upvotes: 0

Views: 290

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

Here's another way, for variety.

as.vector(mapply(`:`, 3*a-2, 3*a))
# [1]  1  2  3  7  8  9 10 11 12

Upvotes: 2

Thomas
Thomas

Reputation: 44527

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.

Upvotes: 2

Related Questions