r - R:按类别查找一个值高于另一个值的年份
问题描述
我有一个数据框,其中包含位置 ( loc
)、位置 ( ) 内的距离dist
、值 ( cumRate
) 和年份 ( year
) 列。
我想比较距离之间的费率,确定哪个更高并找到一年,当一个区域的费率变得高于另一个区域时,如下所示(在第 2 年,距离“100”高于距离“npr ")
[![enter code here][1]][1]
这似乎很容易,但我真的不知道从哪里开始......谢谢您的建议!
虚拟数据:
loc = rep(c("a","b"), each = 6)
dist = rep(c("npr", "100", "npr", "100"), each = 3)
cumRate = c(0,0,4,0,1,2,0,0,1,3,5,7)
year = rep(c(1,2,3), 4)
df = data.frame(loc, dist, cumRate, year)
loc dist cumRate year
1 a npr 0 1
2 a npr 0 2
3 a npr 4 3
4 a 100 0 1
5 a 100 1 2
6 a 100 2 3
7 b npr 0 1
8 b npr 0 2
9 b npr 1 3
10 b 100 3 1
11 b 100 5 2
12 b 100 7 3
绘制数据
windows()
ggplot(df, aes(x = year,
y = cumRate,
fill = dist,
colour = dist)) +
geom_line() +
theme_bw() +
facet_grid(.~ loc)
期望的输出
outDf
loc dist year
a 100 2
b 100 1
解决方案
这是一种不扩散的方法:
library(dplyr)
df %>% group_by(loc, year) %>%
filter(max(cumRate) != min(cumRate)) %>%
arrange(loc, year, desc(cumRate)) %>%
group_by(loc) %>%
slice(1)
# # A tibble: 2 x 4
# # Groups: loc [2]
# loc dist cumRate year
# <fctr> <fctr> <dbl> <dbl>
# 1 a 100 1 2
# 2 b 100 3 1
首先我们删除没有变化的cumRate
年份,然后我们按位置、年份和降序对数据进行排序,并取每个位置的第一行。
推荐阅读
- blazor - 更新 MudBlazor 后,我的带有 NavMenu 的抽屉消失了
- django - 如何更改默认的 django rest_auth 重定向?
- python - 尝试使用 selenium 无头 chrome 进行身份验证时,AWS EC2 超时
- .net - net WCF 客户端配置 htts
- kdb - kdb:使用 \l 加载数据文件(表与列表)
- python - 调试帮助:Python PuLP 中的混合整数线性规划问题
- vue.js - Vue - 在运行功能之前检查数据已设置
- javascript - Chrome 扩展程序:从选项页面重新加载页面
- google-cloud-platform - Google Cloud Build 无法通过我的私有 GitHub 存储库进行身份验证
- python - 最后下采样时如何获得NAN