r - 如何根据名称列表对数据框进行排序?
问题描述
我想根据特殊列表重新排序我的数据框。例如,
t1 <- c(0,0,1,0,0)
t2 <- c(1,1,1,1,1)
t3 <- c(1,2,3,4,5)
b <- c("a","b","c","d","e")
df <-data.frame(t1,t2,t3)
rownames(df) <- b
> df
t1 t2 t3
a 0 1 1
b 0 1 2
c 1 1 3
d 0 1 4
e 0 1 5
list <- c("b","c","a","e","d")
#I want to order the rows follow the order of "list", ideal result is
t1 t2 t3
b 0 1 2
c 1 1 3
a 0 1 1
e 0 1 5
d 0 1 4
我怎样才能做到这一点?先感谢您 :)
解决方案
我们可以使用'list'(这里是a vector
)作为行名来根据它排序(假设'list'和'df'的行名长度相同并且具有相同的值)
df[list,]
# t1 t2 t3
#b 0 1 2
#c 1 1 3
#a 0 1 1
#e 0 1 5
#d 0 1 4
推荐阅读
- excel - 如何根据用户表单组合框选择查询单元格中的数据并将数据复制到用户表单文本框中
- amazon-ecs - AWS ECS - 如何从秘密管理器中检索特定密钥?
- java - 在 PCF 中运行的 Spring Boot 微服务中,Linux 二进制文件应位于何处以通过 ProcessBuilder/Runtime 调用
- shell - 从 Makefile 运行 docker exec 时看不到 shell 提示或输入
- javascript - Chrome 中关于跨域读取阻止的警告
- ruby-on-rails - Route 翻译 Rails 引擎的命名空间路由
- eclipse - 错误常量池中的无效字节标记:19
- sas - 动态定义一个 SAS 哈希
- powershell - IIS AppCmd - 无法在应用程序下创建/配置虚拟目录
- python - 为什么代码不适用于 Python 字典