seq 和 seq_along,两全其美?

use*_*296 3 r

如果我想对两个向量中的所有元素进行编号,向量 1 获取所有奇数,向量 2 获取所有偶数,假设向量的长度为 10,我可以这样做。

seq(1, 10, by=2)
[1] 1 3 5 7 9

seq(2, 11, by=2)
[1]  2  4  6  8 10
Run Code Online (Sandbox Code Playgroud)

但如果我的向量只有一个元素,我会遇到问题:

 seq(2)
[1] 1 2
Run Code Online (Sandbox Code Playgroud)

所以我用:

seq_along(2)
[1] 1
Run Code Online (Sandbox Code Playgroud)

但我不能by=seq_long(). seq_along我如何获得的功能的可靠性seq()


这个例子可能会澄清一些事情。

想象一下我有两个列表:

list1 <- list(4)
list2 <- list(4)
Run Code Online (Sandbox Code Playgroud)

list1必须沿着列表的元素获取偶数名称。 list2列表元素中必须有奇数名称。

我不知道列表元素有多长。

seq_along(list1[[1]]) # this will know to only give one name but I cant make it even

seq(list2[[1]]) # this know to give 1 name
#and
seq(2, list1[[1]], by=2) # this gives me even but too nay names
Run Code Online (Sandbox Code Playgroud)

Mar*_*gan 5

这是一个向 seq_along 添加 'by' 参数的函数:

seq_along_by = function(x, by=1L, from = 1L) (seq_along(x) - 1L) * by + from
Run Code Online (Sandbox Code Playgroud)

和一些测试用例

> seq_along_by(integer(), 2L)
integer(0)
> seq_along_by(1, 2L)
[1] 1
> seq_along_by(1:4, 2L)
[1] 1 3 5 7
> seq_along_by(1:4, 2.2)
[1] 1.0 3.2 5.4 7.6
> seq_along_by(1:4, -2.2)
[1]  1.0 -1.2 -3.4 -5.6
Run Code Online (Sandbox Code Playgroud)