r - 为数据框中的每个组选择前 N 行
问题描述
所以我在下面有一个数据框示例:
Index Country
4.1 USA
2.1 USA
5.2 USA
1.1 Singapore
6.2 Singapore
8.1 Germany
4.5 Italy
7.1 Italy
2.3 Italy
5.9 Italy
8.8 Russia
而且,我打算为数据框中的每组Country获取N 个元素。例如,如果N = 3,那么我将从每个组中取出 3 行,并且如果任何特定组没有像Singapore这样的 N 个元素,那么它将只使用带有 Country 标签Singapore的两条记录就足够了。这同样适用于具有 N 个以上元素的国家标签,例如意大利,因此只需要其中三个。
对于 N = 3,输出数据帧将是:
Index Country
4.1 USA
2.1 USA
5.2 USA
1.1 Singapore
6.2 Singapore
8.1 Germany
4.5 Italy
7.1 Italy
2.3 Italy
8.8 Russia
我在想类似的东西:
aggregate(df, by=list(df$Country), head(df, 3))
但这似乎不起作用。
解决方案
使用中的dplyr
包,tidyverse
您可以执行以下操作:
library(tidyverse)
df <- tribble(
~Index, ~Country
, 4.1, "USA"
, 2.1, "USA"
, 5.2, "USA"
, 1.1, "Singapore"
, 6.2, "Singapore"
, 8.1, "Germany"
, 4.5, "Italy"
, 7.1, "Italy"
, 2.3, "Italy"
, 5.9, "Italy"
, 8.8, "Russia"
)
df %>% # take the dataframe
group_by(Country) %>% # group it by the grouping variable
slice(1:3) # and pick rows 1 to 3 per group
输出:
Index Country
<dbl> <chr>
1 8.1 Germany
2 4.5 Italy
3 7.1 Italy
4 2.3 Italy
5 8.8 Russia
6 1.1 Singapore
7 6.2 Singapore
8 4.1 USA
9 2.1 USA
10 5.2 USA
推荐阅读
- java - Apache FTPClient:将文本从内存写入 FTP 服务器上的文件
- python - Pandas 如果行值包含列表中的项目作为子字符串,则将行值保存到不同的数据框
- angular - Angular,ng-select 问题,在输入区域不显示所选值
- android - 材质主题不支持透明背景
- android - Android Studio 更新到 3.6.x 后未安装 APK
- driver - Linux/PCIe 驱动程序中的 PCIe 设备通信
- excel - 如何让 VBA 在 Microsoft Excel 安全通知的消息框中选择非默认选项?
- perl - 检查数组元素是否未从 XSUB 中定义
- datetime - 日期时间列 PowerBI 中的最早时间
- java - ArrayList,双包含