我在R中使用Tidyverse包。我有一个20行和500列的数据框。我想根据每列最后一行中值的大小对所有列进行排序。
这是一个只有3行和4列的示例:
1 2 3 4,
5 6 7 8,
8 7 9 1
期望的结果是:
3 1 2 4,
7 5 6 8,
9 8 7 1
我搜索了堆栈溢出但无法找到这类问题的答案。
如果我们想使用来自dplyr
的tidyverse
,我们可以使用slice
获取最后一行,然后使用order
命令中的decreasing
来配置列。
library(dplyr)
df[df %>% slice(n()) %>% order(decreasing = TRUE)]
# V3 V1 V2 V4
#1 3 1 2 4
#2 7 5 6 8
#3 9 8 7 1
基数R中的翻译是谁
df[order(df[nrow(df), ], decreasing = TRUE)]
数据
df <- read.table(text = "1 2 3 4
5 6 7 8
8 7 9 1")
以下按最后行值的顺序重新排序数据框列:
df <- data.frame(col1=c(1,5,8),col2=c(2,6,7),col3=c(3,7,9),col4=c(4,8,1))
last_row <- df[nrow(df),]
df <- df[,order(last_row,decreasing = T)]
首先,获取最后一行。然后使用order()函数对它们进行排序并返回重新排序的列。
>df
col3 col1 col2 col4
1 3 1 2 4
2 7 5 6 8
3 9 8 7 1