[英]How to take elements of a numeric vector in R, and create a new vector containing seq from 1:(each element)
Let's say I have a vector called input <- c(8,5,2)
.假设我有一个名为
input <- c(8,5,2)
的向量。 I want to create a new vector in which is essentially c(1:8, 1:5, 1:2)
.我想创建一个新的向量,其中本质上是
c(1:8, 1:5, 1:2)
。 I can do it in the following ugly way:我可以用以下丑陋的方式做到这一点:
input <- c(8,5,2);
newvec <- c();
for(num in input) newvec <- append(newvec, 1:num);
newvec
But I feel like it should be doable in one-line, and I'm probably just oblivious to a simple solution.但我觉得它应该可以在一行中实现,而且我可能只是忘记了一个简单的解决方案。
An easier R
option is sequence
一个更简单的
R
选项是sequence
sequence(input)
#[1] 1 2 3 4 5 6 7 8 1 2 3 4 5 1 2
Or use lapply
and unlist
或者使用
lapply
和unlist
unlist(lapply(input, seq))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.