在此我们解释如何编写一个 R 程序,通过多个列对给定数据框进行排序。这里我们使用内置函数 order() 来实现排序。order() 函数有助于返回一个排列。它将其第一个参数重新排列为升序或降序,并通过后续参数打破平局。order() 的语法如下:
order(…, na.last = TRUE, decreasing = FALSE,
method = c("auto", "shell", "radix"))
这里的点 (....) 是数字、复数、字符或逻辑向量的序列,或一个分类的 R 对象。如果 na.last 为 TRUE,数据中的缺失值将放在最后;如果为 FALSE,则放在最前面,接下来是允许部分匹配的方法。
以下是在 R 程序中按多个列对给定数据框进行排序的步骤。在此 R 程序中,我们直接将数据框传递给内置函数。这里我们使用变量 E、N、S、A、Q 来保存不同类型的向量。调用 data.frame() 函数创建数据框。最后,通过调用 E[with(E, order(N, S)), ] 按多个列对给定数据框进行排序。
步骤 1: 将变量 E、N、S、A、Q 赋值为向量值
步骤 2: 首先打印原始向量值
步骤 3: 通过 E[with(E, order(N, S)), ] 按多个列对给定数据框进行排序
步骤 4: 将结果数据框赋值给 E
步骤 5:打印最终数据框
E = data.frame(
N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
S = c(10, 9.5, 12.2, 11, 8),
A = c(2, 1, 2, 4, 1),
Q = c('yes', 'no', 'yes', 'no', 'no')
)
print("Original dataframe:")
print(E)
print("dataframe after sorting 'N' and 'S' columns:")
E = E[with(E, order(N, S)), ]
print(E)
[1] "Original dataframe:"
name score attempts qualify
1 Jhon 10 2 yes
2 Hialy 9.5 1 no
3 Albert 12.2 2 yes
4 James 11 4 no
5 Delma 8 1 no
[1] "dataframe after sorting 'N' and 'S' columns:"
N S A Q
3 Albert 12.2 2 yes
5 Delma 8.0 1 no
2 Hialy 9.5 1 no
4 James 11.0 4 no
1 Jhon 10.0 2 yes