在apply中使用seq在R中创建索引向量 [英] Using seq within apply to create an index vector in R
问题描述
给定两个相等长度的单独向量:f.start和f.end,我想构造一个序列(由1),从f.start [1]:f.end [1]到f.start [2]:f.end [2] ...到f.start [n]:f.end [n]。
Given two separate vectors of equal length: f.start and f.end, I would like to construct a sequence (by 1), going from f.start[1]:f.end[1] to f.start[2]:f.end[2]...to f.start[n]:f.end[n].
这是一个只有6的例子行。
Here is an example with just 6 rows.
f.start f.end
[1,] 45739 122538
[2,] 125469 202268
[3,] 203563 280362
[4,] 281657 358456
[5,] 359751 436550
[6,] 437845 514644
粗略地说,循环可以做到这一点,但对于较大的数据集(行> 2000)来说非常慢。
Crudely, a loop can do it, but is extremely slow for larger datasets (rows>2000).
f.start<-c(45739,125469,203563,281657,359751,437845)
f.end<-c(122538,202268,280362,358456,436550,514644)
f.ind<-f.start[1]:f.end[1]
for (i in 2:length(f.start))
{
f.ind.temp<-f.start[i]:f.end[i]
f.ind<-c(f.ind,f.ind.temp)
}
我怀疑这可以通过apply()完成,但我还没有弄清楚如何包括两个单独的论点i n申请,并希望得到一些指导。
I suspect this can be done with apply(), but I have not worked out how to include two separate arguments in apply, and would appreciate some guidance.
推荐答案
您可以尝试使用 mapply
或 Map
,它同时迭代你的两个向量。你需要提供函数作为第一个参数:
You can try using mapply
or Map
, which iterates simultaneously on your two vectors. You need to provide the function as first argument:
vec1 = c(1,33,50)
vec2 = c(10,34,56)
unlist(Map(':',vec1, vec2))
# [1] 1 2 3 4 5 6 7 8 9 10 33 34 50 51 52 53 54 55 56
只需更换 vec1
和 vec2
按 f.start
和 f.end
提供全部(f.start< = f.end)
这篇关于在apply中使用seq在R中创建索引向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!