英文:
How to rearrange two columns in R
问题
I have translated the content you provided as requested:
我想要重新排列列 x1 的顺序为 '2016,2017,2018',并且我希望列 x2 按升序排列。列 x3 不应按升序排列。
我的数据
g <- data.frame("x1" = c(2018,2017,2018,2016,2017,2016,2016,2017,2018),
"x2" = c(2,2,5,1,4,3,2,1,1),
"x3" = c(21,22,23,24,25,26,27,28,29))
我正在使用一个大型数据集,但这只是我的数据的示例。
我尝试了下面的公式,但只能重新排列列 `x1` 为 '2016,2017,2018' 的顺序。但是,我无法使列 x2 按升序排列。
```R
# **步骤 1**
cycle_order <- function(x) {
order(ave(x, x, FUN=seq_along), x)
}
# **步骤 2**
X <- g[cycle_order(g$x1), ]
我希望我的预期结果是:
X1: 2016,2017,2018,2016,2017,2018,2016,2017,2018
X2: 1,1,1,2,2,2,3,4,5
X3: 24,28,29,27,22,21,26,25,23
请注意,我只提供了翻译,没有包含任何其他内容。
<details>
<summary>英文:</summary>
I would like to rearrange column x1 in the order '2016,2017,2018' and I want column x2 to be in ascending order. Column x3 should not be in ascending order.
my data
g <- data.frame("x1" = c(2018,2017,2018,2016,2017,2016,2016,2017,2018),
"x2" = c(2,2,5,1,4,3,2,1,1),
"x3" = c(21,22,23,24,25,26,27,28,29))
I am using a large dataset but this is a sample of my data.
I tried the formula below but I was only able to rearrange column `x1` in the order '2016,2017,2018'. However, I was not able to make column x2 in ascending order.
step 1
cycle_order <- function(x) {
order(ave(x, x, FUN=seq_along), x)
}
#**step 2 **
X <- g[cycle_order(g$x1), ]
I would like my expected result to be:
>X1: 2016,2017,2018,2016,2017,2018,2016,2017,2018
>X2: 1,1,1,2,2,2,3,4,5
>X3: 24,28,29,27,22,21,26,25,23
</details>
# 答案1
**得分**: 1
我们可以按特定的列顺序使用 `arrange`。
```R
library(dplyr)
g %>%
arrange(x2, x1, x3)
-输出
x1 x2 x3
1 2016 1 24
2 2017 1 28
3 2018 1 29
4 2016 2 27
5 2017 2 22
6 2018 2 21
7 2016 3 26
8 2017 4 25
9 2018 5 23
英文:
We may use arrange
in a specific order of the columns
library(dplyr)
g %>%
arrange(x2, x1, x3)
-output
x1 x2 x3
1 2016 1 24
2 2017 1 28
3 2018 1 29
4 2016 2 27
5 2017 2 22
6 2018 2 21
7 2016 3 26
8 2017 4 25
9 2018 5 23
答案2
得分: 0
将年份 x1 按 x2 分组并按升序排列。
英文:
Arranging year x1 by_group
x2 in ascending order.
g %>%
group_by(x2) %>%
arrange(x1, .by_group = T) %>%
ungroup()
# A tibble: 9 × 3
x1 x2 x3
<dbl> <dbl> <dbl>
1 2016 1 24
2 2017 1 28
3 2018 1 29
4 2016 2 27
5 2017 2 22
6 2018 2 21
7 2016 3 26
8 2017 4 25
9 2018 5 23
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论