How can I count the number of grouped pairs in which one row's column value is greater than another?

大兔子大兔子 提交于 2020-03-04 20:01:12

问题


I have a dataset (df1) with a number of paired values. One row of the pair is for one year (e.g., 2014), the other for a different year (e.g., 2013). For each pair is a value in the column G. I need a count of the number of pairs in which the G value for the higher year is less than the G value for the lesser year.

Here is my dput for the dataset df1:

structure(list(Name = c("A.J. Ellis", "A.J. Ellis", "A.J. Pierzynski", 
"A.J. Pierzynski", "Aaron Boone", "Adam Kennedy", "Adam Melhuse", 
"Adrian Beltre", "Adrian Beltre", "Adrian Gonzalez", "Alan Zinter", 
"Albert Pujols", "Albert Pujols"), Age = c(37, 36, 37, 36, 36, 
36, 36, 37, 36, 36, 36, 37, 36), Year = c(2018, 2017, 2014, 2013, 
2009, 2012, 2008, 2016, 2015, 2018, 2004, 2017, 2016), Tm = c("SDP", 
"MIA", "TOT", "TEX", "HOU", "LAD", "TOT", "TEX", "TEX", "NYM", 
"ARI", "LAA", "LAA"), Lg = c("NL", "NL", "ML", "AL", "NL", "NL", 
"ML", "AL", "AL", "NL", "NL", "AL", "AL"), G = c(66, 51, 102, 
134, 10, 86, 15, 153, 143, 54, 28, 149, 152), PA = c(183, 163, 
362, 529, 14, 201, 32, 640, 619, 187, 40, 636, 650)), row.names = c(NA, 
13L), class = "data.frame")

Here is a tibble that shows the look of the rows to be checked: https://www.dropbox.com/s/3nbfi9le568qb3s/grouped-pairs.png?dl=0

Here is the code I used to create the tibble:

df1 %>%
  group_by(Name) %>%
  filter(n() > 1)

回答1:


We could arrange the data by Name and Age and check if last value in G is less than first value for each name and count those occurrences with sum.

library(dplyr)
df %>%
  arrange(Name, Age) %>%
  group_by(Name) %>%
  summarise(check = last(G) < first(G)) %>%
  pull(check) %>%
  sum(., na.rm = TRUE)

#[1] 2

If you want the pairs in which the G value for the higher year is less than the G value for the lesser year we could use filter.

df %>%
  arrange(Name, Age) %>%
  group_by(Name) %>%
  filter(last(G) < first(G))

# Name              Age  Year Tm    Lg        G    PA
#  <chr>           <dbl> <dbl> <chr> <chr> <dbl> <dbl>
#1 A.J. Pierzynski    36  2013 TEX   AL      134   529
#2 A.J. Pierzynski    37  2014 TOT   ML      102   362
#3 Albert Pujols      36  2016 LAA   AL      152   650
#4 Albert Pujols      37  2017 LAA   AL      149   636


来源:https://stackoverflow.com/questions/60331378/how-can-i-count-the-number-of-grouped-pairs-in-which-one-rows-column-value-is-g

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!