如何在R中重新排列两列

huangapple go评论66阅读模式
英文:

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 &#39;2016,2017,2018&#39; 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 &#39;2016,2017,2018&#39;. 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:

&gt;X1: 2016,2017,2018,2016,2017,2018,2016,2017,2018

&gt;X2: 1,1,1,2,2,2,3,4,5

&gt;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 %&gt;%
  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

将年份 x1x2 分组并按升序排列。

英文:

Arranging year x1 by_group x2 in ascending order.

g %&gt;% 
  group_by(x2) %&gt;% 
  arrange(x1, .by_group = T) %&gt;% 
  ungroup()
# A tibble: 9 &#215; 3
     x1    x2    x3
  &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
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

huangapple
  • 本文由 发表于 2023年4月19日 21:59:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定