r - 如何结合连续两年的冬季月份
问题描述
我有跨越几年的几个物种的计数数据。我只想查看每年冬季每个物种的丰度动态。问题是冬季跨越两年,即十一月、十二月和明年一月。现在,我想结合连续两年的冬季每个物种的丰度并做一些分析。例如,我想在第一轮中对 2005 年 11 月至 12 月和 2006 年 1 月进行子集化并对此进行一些分析,然后在第二轮中对 2006 年 11 月至 12 月和 2007 年 1 月进行子集化,然后重复相同的分析等等....我怎么能在 R 中做到这一点?
这是数据的示例
date species year month day abundance temp
9/3/2005 A 2005 9 3 3 19
9/15/2005 B 2005 9 15 30 16
10/4/2005 A 2005 10 4 24 12
11/6/2005 A 2005 11 6 32 14
12/8/2005 A 2005 12 8 15 13
1/3/2005 A 2006 1 3 64 19
1/4/2006 B 2006 1 4 2 13
2/10/2006 A 2006 2 10 56 12
2/8/2006 A 2006 1 3 34 19
3/9/2006 A 2006 1 3 64 19
解决方案
我将您的日期列转换为日期类(可能带有lubridate
)并删除年月日列,因为它们是多余的。
然后用季节性年份(定义为年份,除非月份是一月,那么它是上一年)创建一个新列。另一列case_when
用于定义行的季节。
library(dplyr)
library(lubridate)
# converts to date format
df$date <- mdy(df$date)
# add in columns
df <- mutate(df,
season_year = ifelse(month(date) == 1, year(date) - 1, year(date)),
season = case_when(
month(date) %in% c(2, 3, 4) ~ "Spring",
month(date) %in% c(5, 6, 7) ~ "Summer",
month(date) %in% c(8, 9, 10) ~ "Autumn",
month(date) %in% c(11, 12, 1) ~ "Winter",
T ~ NA_character_
))
# date species abundance temp season_year season
# 1 2005-09-03 A 3 19 2005 Autumn
# 2 2005-09-15 B 30 16 2005 Autumn
# 3 2005-10-04 A 24 12 2005 Autumn
# 4 2005-11-06 A 32 14 2005 Winter
# 5 2005-12-08 A 15 13 2005 Winter
# 6 2005-01-03 A 64 19 2004 Winter
# 7 2006-01-04 B 2 13 2005 Winter
# 8 2006-02-10 A 56 12 2006 Spring
# 9 2006-02-08 A 34 19 2006 Spring
# 10 2006-03-09 A 64 19 2006 Spring
然后您可以group_by()
和/或filter()
您的数据进行进一步分析:
df %>%
group_by(season_year) %>%
filter(season == "Winter") %>%
summarise(count = sum(abundance))
# # A tibble: 2 x 2
# season_year count
# <dbl> <int>
# 1 2004 64
# 2 2005 49
推荐阅读
- javascript - How to add the CSS to content page only on clicking of a button from an extension?
- c - recvfrom is not receiving any data, but client is sending the message successfully
- python - Python提取一个内部属性data-display-name
- javascript - jQuery + localStorage - JSON 值检查真假
- javascript - 使用对象属性分配的简写
- c# - 从 .net 核心集成测试项目加载引用的程序集不包括来自测试 API 的引用项目
- java - NativeScriptAngular http请求错误Android 4.2
- javascript - 如何从 Ajax 调用中正确编码的 Java 对象获取阿拉伯语值?
- python - 如何判断具有空字符串值的 python 字符串变量在初始化时是使用单引号还是双引号?
- c++ - Qt5:在 QOAuth2AuthorizationCodeFlow 请求中发送标头