代码之家  ›  专栏  ›  技术社区  ›  maycca

R:按类别查找一个值高于另一个值的年份

r
  •  0
  • maycca  · 技术社区  · 7 年前

    我有一个包含位置的数据框( loc ),位置内距离( dist ),值( cumRate )和年份( year )列。

    我想比较两个距离之间的比率,找出哪一个更高,然后找到一年,当一个区域的比率高于另一个区域的比率时,如下所示(在第二年,距离“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)
    

    enter image description here

    期望输出

    outDf
    
      loc dist  year
       a  100       2
       b  100       1
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Gregor Thomas    7 年前

    这里有一个不扩散的方法:

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

        2
  •  2
  •   zack    7 年前

    我想你需要解开 dist 列:

    library(dplyr)
    library(tidyr)
    
    df %>% 
      spread(dist, cumRate) %>%
      mutate(higher_dist = case_when(
        `100` > npr ~ '100',
        npr > `100` ~ 'npr',
        TRUE ~ 'equal')
      ) %>%
      filter(npr != `100`) %>%
      group_by(loc) %>%
      arrange(year) %>%
      slice(1)
    
      loc    year `100`   npr higher_dist
      <fct> <dbl> <dbl> <dbl> <chr>      
    1 a         2     1     0 100        
    2 b         1     3     0 100