如何按 R 中数据框列表中的第二行从大到小对列进行水平排序?
How to sort the columns horizontally largest-to-smallest by second row in list of data frames in R?
有一个数据框列表,每个数据框的第二行是总行。我想按总数从大到小对列进行水平排序?这是数据框的示例。
structure(list(PROVINCE = c("Percentage", "Total", "11", "11",
"11", "11"), DISTRICT = c("Percentage", "Total", "1", "2", "4",
"4"), SUB_DISTRI = c("Percentage", "Total", "21", "21", "10",
"10"), VILLAGE = c("Percentage", "Total", "14", "5", "22", "24"
), `0` = c("0.111897382265155", "59.930000305176", "0", "9.1700000762939",
"0", "0"), `9` = c("0.545072631055998", "291.930001258852", "0",
"0", "9.6999998092651", "10"), `11` = c("0.0171216252074662",
"9.1700000762939", "9.1700000762939", "0", "0", "0"), `1167` = c("0.325908361471381",
"174.550001144409", "0", "36.6800003051756", "0", "0")), row.names = c(34L,
33L, 1L, 2L, 3L, 4L), class = "data.frame")
您想使用 order
。由于您有四列非数字数据,并且您的数字数据(出于某种原因)被格式化为字符,因此您需要执行以下操作:
df[, c(1:4, order(as.numeric(unlist(
df[2, 5:ncol(df)], use.names=FALSE)), decreasing = TRUE) + 4)]
分解:
df2[2, 5:ncol(df)]
选择第二行和所有数字列
as.numeric(unlist(., use.names = FALSE))
将其转换为数值,以便您可以对它们进行排序
order
returns 排序的位置。 decreasing = TRUE
对 order
他们从大到小说
c(1:4, ... + 4)
需要保留原来的四列(在它们的位置)并相应地调整 order
的输出
有一个数据框列表,每个数据框的第二行是总行。我想按总数从大到小对列进行水平排序?这是数据框的示例。
structure(list(PROVINCE = c("Percentage", "Total", "11", "11",
"11", "11"), DISTRICT = c("Percentage", "Total", "1", "2", "4",
"4"), SUB_DISTRI = c("Percentage", "Total", "21", "21", "10",
"10"), VILLAGE = c("Percentage", "Total", "14", "5", "22", "24"
), `0` = c("0.111897382265155", "59.930000305176", "0", "9.1700000762939",
"0", "0"), `9` = c("0.545072631055998", "291.930001258852", "0",
"0", "9.6999998092651", "10"), `11` = c("0.0171216252074662",
"9.1700000762939", "9.1700000762939", "0", "0", "0"), `1167` = c("0.325908361471381",
"174.550001144409", "0", "36.6800003051756", "0", "0")), row.names = c(34L,
33L, 1L, 2L, 3L, 4L), class = "data.frame")
您想使用 order
。由于您有四列非数字数据,并且您的数字数据(出于某种原因)被格式化为字符,因此您需要执行以下操作:
df[, c(1:4, order(as.numeric(unlist(
df[2, 5:ncol(df)], use.names=FALSE)), decreasing = TRUE) + 4)]
分解:
df2[2, 5:ncol(df)]
选择第二行和所有数字列as.numeric(unlist(., use.names = FALSE))
将其转换为数值,以便您可以对它们进行排序order
returns 排序的位置。decreasing = TRUE
对order
他们从大到小说c(1:4, ... + 4)
需要保留原来的四列(在它们的位置)并相应地调整order
的输出