这个问题是关于R的。
假设我有数据帧df1
:
A B C D E
1 10 1 9 2 1
2 7 10 7 3 10
3 6 5 10 2 2
4 4 9 8 10 5
5 10 10 7 8 8
6 8 1 4 10 3
7 9 10 7 8 2
8 4 10 9 6 4
9 6 9 3 2 7
10 2 4 2 9 9
和数据帧df2
:
B E C A D
1 4 9 2 2 9
2 9 7 3 6 2
3 1 3 4 8 10
4 10 8 7 10 8
5 10 2 7 9 8
6 10 10 7 7 3
7 9 5 8 4 10
8 1 1 9 10 2
9 10 4 9 4 6
10 5 2 10 6 2
假设我没有每个字段的列名。除了行/列顺序(它们包含相同的信息)之外,数据帧是等效的
是否可以对两个数据帧排序而不知道它们的列名在值上完全相同?如何根据数据帧的值排序数据帧,以便它们完全相同/具有完全相同的格式?
即如何使两个数据框看起来都像:(请注意,这只是df1
)
+----+----+----+----+----+
| 10 | 1 | 9 | 2 | 1 |
| 7 | 10 | 7 | 3 | 10 |
| 6 | 5 | 10 | 2 | 2 |
| 4 | 9 | 8 | 10 | 5 |
| 10 | 10 | 7 | 8 | 8 |
| 8 | 1 | 4 | 10 | 3 |
| 9 | 10 | 7 | 8 | 2 |
| 4 | 10 | 9 | 6 | 4 |
| 6 | 9 | 3 | 2 | 7 |
| 2 | 4 | 2 | 9 | 9 |
+----+----+----+----+----+
谢谢!
数据,格式为dput
。
df1 <-
structure(list(A = c(10, 7, 6, 4, 10, 8, 9, 4, 6, 2), B = c(1,
10, 5, 9, 10, 1, 10, 10, 9, 4), C = c(9, 7, 10, 8, 7, 4, 7, 9,
3, 2), D = c(2, 3, 2, 10, 8, 10, 8, 6, 2, 9), E = c(1, 10, 2,
5, 8, 3, 2, 4, 7, 9)), .Names = c("A", "B", "C", "D", "E"), row.names = c(NA,
-10L), class = "data.frame")
df2 <-
structure(list(B = c(4, 9, 1, 10, 10, 10, 9, 1, 10, 5), E = c(9,
7, 3, 8, 2, 10, 5, 1, 4, 2), C = c(2, 3, 4, 7, 7, 7, 8, 9, 9,
10), A = c(2, 6, 8, 10, 9, 7, 4, 10, 4, 6), D = c(9, 2, 10, 8,
8, 3, 10, 2, 6, 2)), .Names = c("B", "E", "C", "A", "D"), row.names = c(NA,
-10L), class = "data.frame")
答案 0 :(得分:0)
为了解决您的问题,您只需要知道order
是它自己的逆。
ordFun <- function(x, y){
i1 <- order(x)
i2 <- order(y)
y[i2][order(i1)]
}
result <- lapply(names(df1), function(nm) ordFun(df1[[nm]], df2[[nm]]))
result <- do.call(cbind.data.frame, result)
names(result) <- names(df1)
result
# A B C D E
#1 10 1 9 2 1
#2 7 10 7 3 10
#3 6 5 10 2 2
#4 4 9 8 10 5
#5 10 10 7 8 8
#6 8 1 4 10 3
#7 9 10 7 8 2
#8 4 10 9 6 4
#9 6 9 3 2 7
#10 2 4 2 9 9