首页 > 解决方案 > 为数据框中的每个组选择前 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))

但这似乎不起作用。

标签: rdataframe

解决方案


使用中的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  

推荐阅读