简体   繁体   English

是否有 R function 根据指定行中的列值重新排列多列?

[英]Is there an R function to re-arrange multiple columns based on column value in a specified row?

I'm trying to relocate multiple columns and sort on their value in the final row of my dataset.我正在尝试重新定位多个列并在我的数据集的最后一行中对它们的值进行排序。 Is there a way to do this in dplyr, or do I need to swap rows and columns so I can just use arrange?在 dplyr 中有没有办法做到这一点,或者我是否需要交换行和列以便我可以只使用排列?

Here is an example:这是一个例子:

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

And my output would ideally be the same data frame but sorted id, A, D, B, C (letter-named columns in the order of their numeric values in the final row).我的 output 理想情况下是相同的数据框,但排序为 id、A、D、B、C(字母命名的列按照最后一行中数值的顺序排列)。

The character row combined with the negative numbers means that when I try to order the rows using the answer suggested below,字符行与负数相结合意味着当我尝试使用下面建议的答案对行进行排序时,

neworder <- order(unlist(df[nrow(df),]))

df[, neworder]

the order produced is D, A, B, C, id.产生的订单是D,A,B,C,id。 I can't figure out why D and A are swapping places.我不明白为什么 D 和 A 会交换位置。

Edit note: Found this in the reopen queue and the only way this makes sense is to restrict the reordering to the columns with letter names whose final row has numeric values.编辑说明:在重新打开队列中找到了它,唯一有意义的方法是将重新排序限制为最后一行具有数值的字母名称的列。 The id column has a letter value in that row. id列在该行中有一个字母值。

Here is a simple method using base R:这是一个使用基数 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]

The new result is order for the lowest to highest based on the values in the last row.新结果是根据最后一行中的值从最低到最高的顺序。

UPDATE To avoid including the first column in the sort, modify the columns passed to the order function. Then add 1 to the result,更新为了避免在排序中包含第一列,修改传递给订单 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM