R 使用 Order() 对数据框进行排序
在数据分析中你可以 分类 根据数据集中的某个变量对数据进行排序。在 R 中,我们可以使用 order() 函数的帮助。在 R 中,我们可以轻松地对连续变量或因子变量的向量进行排序。排列数据可以是 升序 or 降 秩序。
语法:
sort(x, decreasing = FALSE, na.last = TRUE):
争论:
- x:包含连续或因子变量的向量
- 减少:控制排序方法的顺序。默认情况下,降序设置为 `FALSE`。
- 最后:表示 `NA` 的值是否应放在最后
例子1
例如,我们可以创建一个 tibble 数据框并对一个或多个变量进行排序。tibble 数据框是一种新的数据框方法。它改进了数据框的语法,避免了令人沮丧的数据类型格式化,尤其是对于字符到因子的格式化。这也是手动创建数据框的一种便捷方式,这也是我们的目的。要了解有关 tibble 的更多信息,请参阅插图: https://cran.r-project.org/web/packages/tibble/vignettes/tibble.html
library(dplyr) set.seed(1234) data_frame <- tibble( c1 = rnorm(50, 5, 1.5), c2 = rnorm(50, 5, 1.5), c3 = rnorm(50, 5, 1.5), c4 = rnorm(50, 5, 1.5), c5 = rnorm(50, 5, 1.5) ) # Sort by c1 df <-data_frame[order(data_frame$c1),] head(df)
输出:
# A tibble: 6 x 5 ## c1 c2 c3 c4 c5 ## <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 1.481453 3.477557 4.246283 3.686611 6.0511003 ## 2 1.729941 5.824996 4.525823 6.753663 0.1502718 ## 3 2.556360 6.275348 2.524849 6.368483 5.4787404 ## 4 2.827693 4.769902 5.120089 3.743626 4.0103449 ## 5 2.988510 4.395902 2.077631 4.236894 4.6176880 ## 6 3.122021 6.317305 5.413840 3.551145 5.6067027
例子2
# Sort by c3 and c4 df <-data_frame[order(data_frame$c3, data_frame$c4),] head(df)
输出:
# A tibble: 6 x 5 ## c1 c2 c3 c4 c5 ## <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 2.988510 4.395902 2.077631 4.236894 4.617688 ## 2 2.556360 6.275348 2.524849 6.368483 5.478740 ## 3 3.464516 3.914627 2.730068 9.565649 6.016123 ## 4 4.233486 3.292088 3.133568 7.517309 4.772395 ## 5 3.935840 2.941547 3.242078 6.464048 3.599745 ## 6 3.835619 4.947859 3.335349 4.378370 7.240240
例子3
# Sort by c3(descending) and c4(acending) df <-data_frame[order(-data_frame$c3, data_frame$c4),] head(df)
输出:
# A tibble: 6 x 5 ## c1 c2 c3 c4 c5 ## <dbl> <dbl> <dbl> <dbl> <dbl> ## 1 4.339178 4.450214 8.087243 4.5010140 8.410225 ## 2 3.959420 8.105406 7.736312 7.1168936 5.431565 ## 3 3.339023 3.298088 7.494285 5.9303153 7.035912 ## 4 3.397036 5.382794 7.092722 0.7163620 5.620098 ## 5 6.653446 4.733315 6.520536 0.9016707 4.513410 ## 6 4.558559 4.712609 6.380086 6.0562703 5.044277
