如何从向量中获取每三个记录?

发布于 2024-12-10 17:03:27 字数 218 浏览 0 评论 0原文

我有一个向量:

> dput(rn, 20)
c(128L, 241L, 354L, 467L, 580L, 693L, 806L, 919L, 1032L, 1145L, 
1258L, 1371L, 1484L, 1597L, 1710L, 1823L, 1936L, 2049L, 2162L, 
2275L)

如何从该向量中获取每三个记录?

I have a vector:

> dput(rn, 20)
c(128L, 241L, 354L, 467L, 580L, 693L, 806L, 919L, 1032L, 1145L, 
1258L, 1371L, 1484L, 1597L, 1710L, 1823L, 1936L, 2049L, 2162L, 
2275L)

How do I get every third record from this vector?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

演出会有结束 2024-12-17 17:03:27

让回收发挥魔力。

rn[c(FALSE, FALSE, TRUE)]

尽管这个(以及我认为的所有其他答案)失败了 length(rn) length(rn) length(rn) length(rn) length(rn) length(rn) < 3..或许

rn[3L * seq_len(length(rn)/3L)]

Let recycling do it's magic.

rn[c(FALSE, FALSE, TRUE)]

though this (and all the other answers, I think) fails with length(rn) < 3. Maybe

rn[3L * seq_len(length(rn)/3L)]
明月松间行 2024-12-17 17:03:27

使用 seq 创建索引号序列:

> rn[seq(3, 20, 3)]
[1]  354  693 1032 1371 1710 2049

这是有效的,因为 seq 生成以下序列:

seq(from=3, to=20, by=3)
[1]  3  6  9 12 15 18

更一般地说,如果您事先不知道向量的长度,您可以使用 length 计算它:

seq(from=3, to=length(rn), by=3)
[1]  3  6  9 12 15 18

请参阅 ?seq 获取更多帮助。

Use seq to create a sequence of index numbers:

> rn[seq(3, 20, 3)]
[1]  354  693 1032 1371 1710 2049

This works because seq generates the following sequence:

seq(from=3, to=20, by=3)
[1]  3  6  9 12 15 18

More generally, if you don't know the length of your vector in advance, you can calculate it using length:

seq(from=3, to=length(rn), by=3)
[1]  3  6  9 12 15 18

See ?seq for more help.

耳钉梦 2024-12-17 17:03:27

rn[seq(3,length(rn),3)] # 30 个字符

rn[seq(3,length(rn),3)] # 30 chars

世界和平 2024-12-17 17:03:27

也许喜欢这样?

> x <- c(128L, 241L, 354L, 467L, 580L, 693L, 806L, 919L, 1032L, 1145L, 
+ 1258L, 1371L, 1484L, 1597L, 1710L, 1823L, 1936L, 2049L, 2162L, 
+ 2275L)
> 
> x[seq(3, length(x), 3)]
[1]  354  693 1032 1371 1710 2049

Mayby like this?

> x <- c(128L, 241L, 354L, 467L, 580L, 693L, 806L, 919L, 1032L, 1145L, 
+ 1258L, 1371L, 1484L, 1597L, 1710L, 1823L, 1936L, 2049L, 2162L, 
+ 2275L)
> 
> x[seq(3, length(x), 3)]
[1]  354  693 1032 1371 1710 2049
烟雨扶苏 2024-12-17 17:03:27

seq() 本身就可以做一些很好的事情:x[seq(x)%%3==0] 就可以了。从技术上讲,x[seq_along(x)%%3==0] 更快,但大多数时候您不会在意。

例如,

> letters[seq(letters)%%3==0]
[1] "c" "f" "i" "l" "o" "r" "u" "x"

seq() by itself does nice things: x[seq(x)%%3==0] will do the trick. Technically x[seq_along(x)%%3==0] is faster, but most of the time you won't care.

For example,

> letters[seq(letters)%%3==0]
[1] "c" "f" "i" "l" "o" "r" "u" "x"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文