1
votes

Comment agréger dans R avec des conditions

x <- data.frame(names=c("peter","peter", "jacob", "jacob"),
            some_score =c(5,8,6,8),
            xDate = as.Date(c("2018-01-01", "2019-01-01" , "2018-06-08", 
"2019-10-22"))
)In this dataframe in need to aggregate so i get the latest score for each name 
(peter= 8 and Jacob=8)Is there a fast way to do that? Right now i am creating two aggregate dataframes and linking them. But this seems inefficient
r

1 commentaires

Salut, j'ai remarqué que vous n'avez jusqu'à présent accepté aucune réponse aux questions posées. Ce n'est pas une bonne pratique sur SO. Veuillez envisager d'accepter une réponse qui vous convient le mieux pour cette question et toutes vos autres questions également. Lisez stackoverflow.com/help/someone-answers


5 Réponses :


2
votes
> aggregate(x,list(x$names),tail,1)
  Group.1 names some_score      xDate
1   jacob jacob          8 2019-10-22
2   peter peter          8 2019-01-01
assuming your dataframe is sorted, otherwise sort it first by time.

0 commentaires

3
votes

Nous pourrions obtenir la ligne avec un maximum de xDate pour chaque noms .

Cela peut être fait en utilisant dplyr

library(data.table)
setDT(x)[, .SD[which.max(xDate)], names]

Ou data.table

library(dplyr)
x %>% group_by(names) %>% slice(which.max(xDate))

#  names  some_score  Date     
#   <chr>      <dbl> <date>    
#1 jacob          8 2019-10-22
#2 peter          8 2019-01-01


0 commentaires

1
votes

Une autre solution:

library(magrittr)

x %>% 
  dplyr::group_by(names) %>% 
  dplyr::filter(xDate == max(xDate))


0 commentaires

1
votes

Doublure Base R one:

data.frame(do.call("rbind", lapply(split(x, x$names), function(x){x[which.max(x$xDate),]})), 
           row.names = NULL)


0 commentaires

0
votes

le package dplyr est une excellente option pour votre question.

x <- data.frame(names=c("peter","peter", "jacob", "jacob"),
                some_score =c(5,8,6,8),
                xDate = as.Date(c("2018-01-01", "2019-01-01" , "2018-06-08", 
                                  "2019-10-22")))
library(dplyr)
x %>% 
  group_by(names) %>% 
  summarise(max_some_score = max(some_score))


0 commentaires