首页 > 解决方案 > 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

标签: r

解决方案


这是一种不扩散的方法:

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年份,然后我们按位置、年份和降序对数据进行排序,并取每个位置的第一行。


推荐阅读