简体   繁体   English

如何在 R 中获取数字向量的元素,并创建一个包含 seq 从 1:(每个元素)的新向量

[英]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或者使用lapplyunlist

unlist(lapply(input, seq))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 R 中创建一个数值向量的位置向量? - How to create a vector of positions of a numeric vector in R? 从 R 中的数字向量的每个元素中提取第一个数字 - Extract first digit from each element of a numeric vector in R R:如何将向量中的元素放入新向量的特定位置 - R: how to get elements from a vector into specific positions of a new vector 如何将包含等号的新元素添加到R中的字符向量 - How to add a new element containing an equals sign to a character vector in R 我有一个向量,其元素包含多个数字。 如何对每个元素中的数字求和并创建新的向量? - I have a vector whose elements contain multiple numbers. How do I sum numbers inside each element and create a new vector? R - 从包含数字的向量元素中删除 - R - Remove from vector elements containing a number 每次创建一个从 1 到 n 的数值向量,给定一个 ns 的向量 - Create a numeric vector from 1 to n each time, given a vector of ns 将字符向量的每个元素与第二个向量r的所有元素连接起来 - concatenate each element of character vector with all elements of a second vector r 如何为R中的向量中的每个元素创建一个闭包? - How to create one closure for each of the elements in a vector in R? 用R中am * n数值矩阵的每一列的正元素之和创建向量 - Create a vector with the sum of the positive elements of each column of a m*n numeric matrix in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM