如何从向量中获取每三个记录?
我有一个向量:
> 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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
让回收发挥魔力。
尽管这个(以及我认为的所有其他答案)失败了
length(rn)
length(rn)
length(rn)
length(rn)
length(rn)
length(rn) < 3.
.或许Let recycling do it's magic.
though this (and all the other answers, I think) fails with
length(rn) < 3
. Maybe使用
seq
创建索引号序列:这是有效的,因为
seq
生成以下序列:更一般地说,如果您事先不知道向量的长度,您可以使用
length
计算它:请参阅
?seq
获取更多帮助。Use
seq
to create a sequence of index numbers:This works because
seq
generates the following sequence:More generally, if you don't know the length of your vector in advance, you can calculate it using
length
:See
?seq
for more help.rn[seq(3,length(rn),3)] # 30 个字符
rn[seq(3,length(rn),3)] # 30 chars
也许喜欢这样?
Mayby like this?
seq()
本身就可以做一些很好的事情:x[seq(x)%%3==0]
就可以了。从技术上讲,x[seq_along(x)%%3==0]
更快,但大多数时候您不会在意。例如,
seq()
by itself does nice things:x[seq(x)%%3==0]
will do the trick. Technicallyx[seq_along(x)%%3==0]
is faster, but most of the time you won't care.For example,