我需要在R中编写一个函数,以返回列值大于0的系列中的第一个日期。我想在数据框中标识每年的该日期。
例如,给定此示例数据...
Date Year Catch
3/12/2001 2001 0
3/19/2001 2001 7
3/24/2001 2001 9
4/6/2002 2002 12
4/9/2002 2002 0
4/15/2002 2002 5
4/27/2002 2002 0
3/18/2003 2003 0
3/22/2003 2003 0
3/27/2003 2003 15
我希望R传回catch> 0的每年的第一个日期
Year Date
2001 3/19/2001
2002 4/6/2002
2003 3/27/2003
我一直在使用下面的min函数,但是它仅返回行号,而我无法在数据框中返回每年的值。
min(which(data$Catch > 0))
我是用R语言编写自己的函数的新手。任何帮助将不胜感激。谢谢。
最佳答案
library(dplyr)
df1 %>%
group_by(Year) %>%
slice(which.max(Catch > 0))
# # A tibble: 3 x 3
# # Groups: Year [3]
# Date Year Catch
# <date> <int> <int>
# 1 2001-03-19 2001 7
# 2 2002-04-06 2002 12
# 3 2003-03-27 2003 15
数据:
df1 <-
structure(list(Date = structure(c(11393, 11400, 11405, 11783,
11786, 11792, 11804, 12129, 12133, 12138), class = "Date"), Year = c(2001L,
2001L, 2001L, 2002L, 2002L, 2002L, 2002L, 2003L, 2003L, 2003L
), Catch = c(0L, 7L, 9L, 12L, 0L, 5L, 0L, 0L, 0L, 15L)), .Names = c("Date",
"Year", "Catch"), row.names = c(NA, -10L), class = "data.frame")