[英]R dplyr summarise one column value based on index of fun(another column)
我有一個數據框,並希望最后顯示所需的輸出。 相反,我在中間得到NA輸出。 有沒有辦法用dplyr做我想做的事情?
x <- c(1234, 1234, 1234, 5678, 5678)
y <- c(95138, 30004, 90038, 01294, 15914)
z <- c('2014-01-20', '2014-10-30', '2015-04-12', '2010-2-28', '2015-01-01')
df <- data.frame(x, y, z)
df$z <- as.Date(df$z)
df %>% group_by(x) %>% summarise(y = y[max(z)])
What I get:
x y
1 1234 NA
2 5678 NA
Desired Output:
x y
1 1234 90038
2 5678 15914
您可以嘗試使用which.max
來獲取可用於對'y'元素進行子集化的max
的數字索引。 使用max
只給出z
的最大值。
df %>%
group_by(x) %>%
summarise(y= y[which.max(z)])
# x y
#1 1234 90038
#2 5678 15914
在dplyr
使用filter
和max
。
df%>%group_by(x)%>%filter(z==max(z))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.