【发布时间】:2020-10-23 18:42:54
【问题描述】:
我有一个如下图所示的数据框
test_df <- data.frame("subject_id" = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),
"date_1" = c("01/01/2003", "12/31/2007", "12/30/2008", "12/31/2005",
"01/01/2007", "01/01/2013", "12/31/2008", "03/04/2006",
"12/31/2009", "01/01/2015", "01/01/2009"))
我想做的是
-
按升序排列每个主题的日期(按组内按升序排列)
-
根据以下标准删除每个主题的日期记录(年份无关紧要):
2a。如果主题的第一条记录是 1 月 1 日,则仅删除 12 月 31 日的记录 例如:subject_id = 1
2b。如果主题的第一条记录是 12 月 31 日,则仅删除 1 月 1 日的记录 例如:subject_id = 2
2c。如果主题在其非第一条记录中同时具有 12 月 31 日和 1 月 1 日(即从第二条记录到其记录结束),则仅删除 12 月 31 日的记录 ex:subject_id = 3
我正在尝试以下方法
sorted <- test_df %>% arrange(date_1,group_by = subject_id) #Am I right in sorts the dates within group?
test_df$month = month(test_df$date_1) #get the month
test_df$day = day(test_df$date_1) #get the year
filter(test_df, month==12 and day == 31) # doesn't work here
您能否帮助我了解如何根据我的条件过滤掉记录?
我希望我的输出如下所示
【问题讨论】:
-
group_by=内的arrange应该做什么?你的意思是arrange(date_1) %>% group_by(subject_id)? (不,无论分组如何安排(尝试mtcars %>% group_by(cyl) %>% arrange(mpg) %>% print(n=99)并看到6s 中间有一个8)。 -
是的,我的意思是
arrange(date_1) %>% group_by(subject_id)
标签: r datetime filter dplyr lubridate