首页 > 解决方案 > R:如何使用 group_map 在 group_by 之后对数据帧进行排序?

问题描述

鉴于此,我有一个数据框如下:

dt <- data.frame(year = sample(c(2000:2019),100 ),
           month = sample(c(1:12),100 ),
           paitent_ID = sample(c(1:50),100,replace = T )

我需要groupby使用数据集然后使用和paitent_ID 对每个组进行排序。yearmonth

这是我尝试过的:

library(dplyr)

dt %>% 
  group_by(paitent_ID) %>%
  group_map( ~ order(year, month)   )

但是,它抱怨:

Error in order(year, month) : object 'year' not found

标签: r

解决方案


我们可以使用arrange而不是order

library(dplyr)
dt %>% 
  group_by(paitent_ID) %>%
  group_map(  ~ .x %>%
                    arrange(year, month))
#[[1]]
# A tibble: 4 x 2
#   year month
#  <int> <int>
#1  2003    10
#2  2009    12
#3  2013     3
#4  2013     6

#[[2]]
# A tibble: 6 x 2
#   year month
#  <int> <int>
#1  2000     6
#2  2000     9
#3  2006     8
#4  2009     3
#5  2015    12
#6  2017    10
#...

推荐阅读