如何从R中的data.frame中检索基于特定变量的极端年份数据?
我知道使用下面的如何从R中的data.frame中检索基于特定变量的极端年份数据?,r,dataframe,sorting,ggplot2,tidyverse,R,Dataframe,Sorting,Ggplot2,Tidyverse,我知道使用下面的code生成的plot会非常混乱,因为数据是使用均匀分布生成的。我想选择仅5年,我们根据变量A观察到最高值。这意味着,变量X的值可能不是高值,因为我们根据变量A调节选择。任何特定年份的多个峰值应视为一次发生。一旦对前5年进行了排序,我希望有一个图如下所示 library(tidyverse) library(lubridate) set.seed(1500) FakeData <- data.frame(Date = seq(as.Date("2001-01-
code
生成的plot
会非常混乱,因为数据是使用均匀分布生成的。我想选择仅5年,我们根据变量A观察到最高值。这意味着,变量X
的值可能不是高值,因为我们根据变量A
调节选择。任何特定年份的多个峰值应视为一次发生。一旦对前5年进行了排序,我希望有一个图
如下所示
library(tidyverse)
library(lubridate)
set.seed(1500)
FakeData <- data.frame(Date = seq(as.Date("2001-01-01"), to= as.Date("2010-12-31"), by="day"),
A = runif(3652, 10,100),
X = runif(3652, 5,500)) %>%
mutate(Year = year(Date), JDay = yday(Date))
ggplot(FakeData, aes(JDay, A, col=as.factor(Year)))+
geom_line()+
theme_bw() + labs(col = "Year", x = "Month of the year", y = "Levels (m)")+
theme(axis.text = element_text(size = 14), axis.title = element_text(size = 16, face = "bold"))+
scale_x_continuous(breaks = c(1,32,60,91,121,152,182,213,244,274,305,335),
labels = c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
limits = c(0,365), expand = c(0, 0))
库(tidyverse)
图书馆(lubridate)
种子集(1500)
伪造数据%
突变(年=年(日期),JDay=yday(日期))
ggplot(伪造数据,不良事件(JDay,A,col=as.factor(Year)))+
geom_线()+
theme_bw()+实验室(col=“年”,x=“一年中的一个月”,y=“级别(m)”)+
主题(axis.text=element\u text(size=14),axis.title=element\u text(size=16,face=“bold”))+
刻度x连续(断开=c(1,32,60,9112115218221324274305335),
标签=c(“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”),
极限=c(0365),展开=c(0,0))
输出
例如,在下图中,我正在绘制将近38年的数据,然而,我只对5年感兴趣,其中级别的值最高。因此,我只想选择这五年作进一步分析。
这就是你要找的吗
库(tidyverse)
图书馆(lubridate)
查找每一年中A的最大值,按降序排序,并提取前五年用作完整数据集的过滤器以进行打印
top_yrs <-
FakeData %>%
group_by(Year) %>%
summarise(maxA = max(A)) %>%
arrange(desc(maxA)) %>%
top_n(5)
FakeData %>%
filter(Year %in% top_yrs$Year) %>%
ggplot(aes(JDay, A, col=as.factor(Year)))+
geom_line()+
theme_bw() + labs(col = "Year", x = "Month of the year", y = "Levels (m)")+
theme(axis.text = element_text(size = 14), axis.title = element_text(size = 16, face = "bold"))+
scale_x_continuous(breaks = c(1,32,60,91,121,152,182,213,244,274,305,335),
labels = c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"),
limits = c(0,365), expand = c(0, 0))
#> Warning: Removed 1 row(s) containing missing values (geom_path).
top\u yrs%
组别(年份)%>%
总结(最大值=最大值(A))%>%
排列(描述(最大值))%>%
顶部(5)
伪造数据%>%
过滤器(年百分比在%top\U yrs$年中)%>%
ggplot(不良事件(JDay,A,col=as.factor(年份)))+
geom_线()+
theme_bw()+实验室(col=“年”,x=“一年中的一个月”,y=“级别(m)”)+
主题(axis.text=element\u text(size=14),axis.title=element\u text(size=16,face=“bold”))+
刻度x连续(断开=c(1,32,60,9112115218221324274305335),
标签=c(“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”),
极限=c(0365),展开=c(0,0))
#>警告:已删除包含缺失值的1行(几何路径)。
由(v0.3.0)FakeData%%>%group\u by(year)%%>%filter(which.max(A))
于2020-07-08创建。对我来说,这似乎是一个过滤的问题。