如何在R中重新排列两列

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

How to rearrange two columns in R

问题

I have translated the content you provided as requested:

  1. 我想要重新排列列 x1 的顺序为 '2016,2017,2018',并且我希望列 x2 按升序排列。列 x3 不应按升序排列。
  2. 我的数据

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))

  1. 我正在使用一个大型数据集,但这只是我的数据的示例。
  2. 我尝试了下面的公式,但只能重新排列列 `x1` '2016,2017,2018' 的顺序。但是,我无法使列 x2 按升序排列。
  3. ```R
  4. # **步骤 1**
  5. cycle_order <- function(x) {
  6. order(ave(x, x, FUN=seq_along), x)
  7. }
  8. # **步骤 2**
  9. 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

  1. 请注意,我只提供了翻译,没有包含任何其他内容。
  2. <details>
  3. <summary>英文:</summary>
  4. 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.
  5. 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))

  1. I am using a large dataset but this is a sample of my data.
  2. 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), ]

  1. I would like my expected result to be:
  2. &gt;X1: 2016,2017,2018,2016,2017,2018,2016,2017,2018
  3. &gt;X2: 1,1,1,2,2,2,3,4,5
  4. &gt;X3: 24,28,29,27,22,21,26,25,23
  5. </details>
  6. # 答案1
  7. **得分**: 1
  8. 我们可以按特定的列顺序使用 `arrange`
  9. ```R
  10. library(dplyr)
  11. g %>%
  12. arrange(x2, x1, x3)

-输出

  1. x1 x2 x3
  2. 1 2016 1 24
  3. 2 2017 1 28
  4. 3 2018 1 29
  5. 4 2016 2 27
  6. 5 2017 2 22
  7. 6 2018 2 21
  8. 7 2016 3 26
  9. 8 2017 4 25
  10. 9 2018 5 23
英文:

We may use arrange in a specific order of the columns

  1. library(dplyr)
  2. g %&gt;%
  3. arrange(x2, x1, x3)

-output

  1. x1 x2 x3
  2. 1 2016 1 24
  3. 2 2017 1 28
  4. 3 2018 1 29
  5. 4 2016 2 27
  6. 5 2017 2 22
  7. 6 2018 2 21
  8. 7 2016 3 26
  9. 8 2017 4 25
  10. 9 2018 5 23

答案2

得分: 0

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

英文:

Arranging year x1 by_group x2 in ascending order.

  1. g %&gt;%
  2. group_by(x2) %&gt;%
  3. arrange(x1, .by_group = T) %&gt;%
  4. ungroup()
  5. # A tibble: 9 &#215; 3
  6. x1 x2 x3
  7. &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  8. 1 2016 1 24
  9. 2 2017 1 28
  10. 3 2018 1 29
  11. 4 2016 2 27
  12. 5 2017 2 22
  13. 6 2018 2 21
  14. 7 2016 3 26
  15. 8 2017 4 25
  16. 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:

确定