r - 基于R中数据框中组内的向量对列值重新排序
问题描述
我有一个数据框如下:
df <- data.frame("QuarterYear" = c("2019 Q1","2019 Q1","2019 Q2","2019 Q2","2019 Q3","2019 Q3","2019 Q3"), "Size" = c("Medium","Small","Large","Medium","Large","Medium","Small"),
"percentage" = c(98,2,29,71,13,74,13))
QuarterYear Size percentage
1 2019 Q1 Medium 98
2 2019 Q1 Small 2
3 2019 Q2 Large 29
4 2019 Q2 Medium 71
5 2019 Q3 Large 13
6 2019 Q3 Medium 74
7 2019 Q3 Small 13
我有一个向量:
size <- c("Small","Medium","Large")
我需要Size
根据每个QuarterYear的向量大小来排列列
预期输出如下:
QuarterYear Size percentage
1 2019 Q1 Small 2
2 2019 Q1 Medium 98
3 2019 Q2 Medium 71
4 2019 Q2 Large 29
5 2019 Q3 Small 13
6 2019 Q3 Medium 74
7 2019 Q3 Large 13
我怎样才能在 R 中实现这一点?
提前致谢!!
解决方案
这是一个data.table
解决方案:
library(data.table)
df = data.table(df)
setorder(df, QuarterYear, -Size)
QuarterYear Size percentage
1: 2019 Q1 Small 2
2: 2019 Q1 Medium 98
3: 2019 Q2 Medium 71
4: 2019 Q2 Large 29
5: 2019 Q3 Small 13
6: 2019 Q3 Medium 74
7: 2019 Q3 Large 13
推荐阅读
- python - Python 属性装饰器和昂贵的计算
- jupyter-notebook - Jupyter 无法查看或创建新笔记本
- python - Python TabError:第 32 行
- qt - Qt Linux Mint 19.2 QSslSocket
- typescript - 具有实现类返回类型的打字稿静态函数
- android - 如何使用 getRawX()/getRawY() 指针 Android 处理多点触控
- angular9 - 无法绑定到“树”,因为它不是 Angular 9 中“树表”的已知属性
- java - 使用数组列表而不是数组
- python - 自动化 python 脚本每 2 小时运行一次并生成 csv 文件
- pandas - 根据 Pandas 中两列之间的匹配查找值