0

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I think you answered my follow up question already. Say I have a different function that returns multiple elements and I want to apply this function to each element in the original list, so I should call this function inside your defined "function".
@Jin Makes sense. Yes, that's what you could do.
2

Here's another way, for variety.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.