创建由“from"和“to"向量定义的整数序列 [英] Create integer sequences defined by 'from' and 'to' vectors

查看:52
本文介绍了创建由“from"和“to"向量定义的整数序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量定义开始(从)索引和结束(到)索引:

I have two vectors which define start (from) indices and finish (to) indices:

Start = c(1, 10, 20)
Finish = c(9, 19, 30)

我想沿着两个向量创建一个所有 Start:Finish 序列的列表,即生成序列 Start[1]:Finish[1] (Start[1]:Finish[1]>1:9);Start[2]:Finish[2],依此类推.

I want to create a list of all Start:Finish sequences along the two vectors, i.e. generate the sequences Start[1]:Finish[1] (1:9); Start[2]:Finish[2], and so on.

## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30

最好采用某种矢量化方式.'Start' 向量中的值将始终大于 'Finish' 向量中的相应元素.

Preferably in some vectorized way. The values in 'Start' vector will always be larger than the corresponding elements in 'Finish' vector.

推荐答案

只需使用mapply:

Start = c(1,10,20)
Finish = c(9,19,30)
mapply(":", Start, Finish)
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30
## 

当然,您也可以使用 Vectorize,但这只是 mapply 的包装器.但是,Vectorize 不能与原始函数一起使用,因此您必须指定 seq.default 而不是 seqseq.int.

You could, of course, also use Vectorize, but that's just a wrapper for mapply. However, Vectorize cannot be used with primitive functions, so you'll have to specify seq.default rather than seq, or seq.int.

示例:

Vectorize(seq.default)(Start, Finish)
## [[1]]
## [1] 1 2 3 4 5 6 7 8 9
## 
## [[2]]
##  [1] 10 11 12 13 14 15 16 17 18 19
## 
## [[3]]
##  [1] 20 21 22 23 24 25 26 27 28 29 30
## 

这篇关于创建由“from"和“to"向量定义的整数序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆