[英]Is there an R function to re-arrange multiple columns based on column value in a specified row?
我正在嘗試重新定位多個列並在我的數據集的最后一行中對它們的值進行排序。 在 dplyr 中有沒有辦法做到這一點,或者我是否需要交換行和列以便我可以只使用排列?
這是一個例子:
df <- data.frame(id = c("q", "w", "e", "t", "d", "r"),
A=c(22, 25, 29, 13, 22, -8),
B=c(12, 10, 6, 6, 8, 11),
C=c(NA, 15, 15, 18, 22, 13),
D=c(90, 4, 3, 6, -6, -6))
我的 output 理想情況下是相同的數據框,但排序為 id、A、D、B、C(字母命名的列按照最后一行中數值的順序排列)。
字符行與負數相結合意味着當我嘗試使用下面建議的答案對行進行排序時,
neworder <- order(unlist(df[nrow(df),]))
df[, neworder]
產生的訂單是D,A,B,C,id。 我不明白為什么 D 和 A 會交換位置。
編輯說明:在重新打開隊列中找到了它,唯一有意義的方法是將重新排序限制為最后一行具有數值的字母名稱的列。 id
列在該行中有一個字母值。
這是一個使用基數 R 的簡單方法:
df <- data.frame(A=c(22, 25, 29, 13, 22, 30),
B=c(12, 10, 6, 6, 8, 11),
C=c(NA, 15, 15, 18, 22, 13))
#get the last row and establish the order
neworder <- order(unlist(df[nrow(df),]))
df[, neworder]
新結果是根據最后一行中的值從最低到最高的順序。
更新為了避免在排序中包含第一列,修改傳遞給訂單 function 的列。然后將結果加 1,
#get the last row and establish the order
# selecting only the desired columns
neworder <- order(unlist(df[nrow(df), 2:5]))
#need to add the first column back onto the column
df[, c(1, (neworder+1))]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.