首页 > 解决方案 > 根据行值对 df 中的列重新排序

问题描述

我有一个具有这种结构的df:

id v1 v2 v3
1  1  2  3
2  4  4  1
3  1  1  1

并希望根据第一行的值对列进行重新排序,如下所示:

id v3 v2 v1
1  3  2  1
2  1  4  4
3  1  1  1

标签: rtidyverse

解决方案


We subset the first row without the first column, unlist, order on descending, then add 1, concatenate the index of first column to do the reordering

df1[c(1, 1 + order(-unlist(df1[1, -1])))]

-output

#  id v3 v2 v1
#1  1  3  2  1
#2  2  1  4  4
#3  3  1  1  1

data

df1 <- structure(list(id = 1:3, v1 = c(1L, 4L, 1L), v2 = c(2L, 4L, 1L
), v3 = c(3L, 1L, 1L)), class = "data.frame", row.names = c(NA, 
-3L))

推荐阅读