英文:
How to reverse the order of each two consecutive elements in a vector?
问题
我想要反转每两个连续元素的顺序,如下所示:
2 1 4 3 6 5
英文:
Let's say I have the following vector
x = c(1,2,3,4,5,6)
I wish to reverse the order of each two consecutive elements as follows
2 1 4 3 6 5
答案1
得分: 3
这是一个想法,
c(rbind(x[c(FALSE, TRUE)], x[c(TRUE, FALSE)]))
# [1] 2 1 4 3 6 5
英文:
Here is an idea,
c(rbind(x[c(FALSE, TRUE)], x[c(TRUE, FALSE)]))
# [1] 2 1 4 3 6 5
答案2
得分: 3
你也可以这样做:
as.vector(matrix(x, nrow = 2)[2:1, ])
[1] 2 1 4 3 6 5
英文:
You could also do
as.vector(matrix(x, nrow = 2)[2:1, ])
[1] 2 1 4 3 6 5
答案3
得分: 3
另一种可能性:
x[seq_along(x) + c(1, -1)]
# [1] 2 1 4 3 6 5
英文:
Another possibility:
x[seq_along(x) + c(1, -1)]
# [1] 2 1 4 3 6 5
答案4
得分: 2
你可以使用 ave
+ rev
来按组反转向量:
ave(x, (seq_along(x) + 1) %/% 2, FUN = rev)
#[1] 2 1 4 3 6 5
英文:
You can use ave
+ rev
to reverse the vector by group:
ave(x, (seq_along(x) + 1) %/% 2, FUN = rev)
#[1] 2 1 4 3 6 5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论