簡體   English   中英

R:分組匯總后得到第二個值

[英]R: Getting Second Value After Grouping and Summarizing

各種 R 函數使使用 group_by 和 summarize 從分組變量中提取值變得容易。 因此,在生成的 dataframe 中,我可以使用 group_by 和 summarize 來創建,例如,一個包含每個組內變量的最大值或最小值的新列。 意思是,有了這些數據:

name, value
foo, 100
foo, 200
foo, 300
bar, 400
bar, 500
bar, 600

我可以輕松獲得每個名稱值的最大值或最小值:

group_by(name) %>% summarize(maxValue = max(value)

但是假設我想要每個名字的第二個值? 意思是假設我希望我的結果是

name maxValue secondValue
foo 300 200
bar 600 500

換句話說,我該如何填寫這個空白:

df %>% group_by(name) %>% 
summarize(maxValue = max(value), 
  secondValue = _________)

感謝來自 r 新手的任何幫助!

dplyr 有方便的nth() function 從列表中提取第 n 個元素。

df %>% group_by(name) %>% 
   summarize(maxValue = max(value), 
             secondValue =nth(value, 2, order_by = value))

這是一種方法,從第二次計算中排除最大值。

df %>% 
  group_by(name) %>% 
  summarize(maxValue = max(value), 
    secondValue = max(value[which.max(value) != row_number()]))
# A tibble: 2 × 3
  name  maxValue secondValue
  <chr>    <int>       <int>
1 bar        600         500
2 foo        300         200

數據

df <- structure(list(name = c("foo", "foo", "foo", "bar", "bar", "bar"
), value = c(100, 400, 300, 400, 500, 600)), row.names = c(NA,
-6L), class = "data.frame")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM