[英]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. 尽管我知道如何在Python和Java中执行此操作,但并不熟悉如何在R中实现此功能。尤其是我知道R在循环中非常慢,并且动态增长列表很慢。
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. 假设我有一个vector(list)a <-c(1,3,4),我想拥有一个由以下规则的元素组成的列表b,来自a的任何元素k包括
3*k-2:3*k
列表中的3*k-2:3*k
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? 现在更普遍的是,如果我有一个rule(function)f(k),如何将返回值附加到新列表中?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.