r - 根据行值对 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
解决方案
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))
推荐阅读
- salesforce - System.TypeException: You are already logged in
- python - 如何阻止估计器恢复每次训练的权重和全局步骤
- python - 用于在 Excel 中导出的嵌套字典顺序或 pandas 列的顺序
- sqlite - React native sqlite 如何在 Flatlist 上从数据库中呈现数据(JSON 类型)?
- java - NoClassDefFoundError 如果在主方法之外调用类
- angular - 访问 WebApi 时不允许使用 Angular 5 HTTP get 方法
- postgresql - 在数据目录从 PostgreSQL 8.4.8 升级到 PostgreSQL 9.5.2 期间,日志(很少)出现两次
- c# - 在 Visual Studio 中随机化用户代理 GeckoFX
- synchronization - Netdrive 和同步文件夹 (Nextcloud) 之间的 MS Office 锁定文件(所有者文件)行为不同
- javascript - 我可以发送文件上传的默认值吗?