0
votes

This should be a simple question. I tried to rank "date" within each group (name) and save the rank output as rank_date.

However, I kept receiving the error "Error in df %>% group_by(name) %>% rank_date <- mutate(df, rank = order(score, : could not find function "%>%<-""

df = data.frame(name=c("A","A","A","B","C","D"), score = c("03/21/2021", "04/21/2021", "05/21/2021", "06/21/2021","07/21/2021","03/21/2021"))
df$score = as.Date(df$score,"%m/%d/%Y")
df %>% 
    group_by(name)%>% 
  rank_date<-mutate(df, rank=order(score, decreasing=TRUE))
2
your mutate is not correct i.e. df %>% group_by(name) %>%mutate(rank_date = order(score, decreasing = TRUE))akrun
Hi @akrun, I tried what you said. "rank_date<-mutate(rank_date =order(score, decreasing=TRUE))" and the new error is "Error in order(score, decreasing = TRUE) : object 'score' not found".Xian Zhao

2 Answers

4
votes

You should place the final object, that should store the result, at the beginning:

library(dplyr)
df <- data.frame(name=c("A","A","A","B","C","D"), score = c("03/21/2021", "04/21/2021", "05/21/2021", "06/21/2021","07/21/2021","03/21/2021"))
df$score = as.Date(df$score,"%m/%d/%Y")
df <- df %>%
  group_by(name) %>%
  mutate(rank_date = order(score, decreasing = TRUE))

df
#> # A tibble: 6 x 3
#> # Groups:   name [4]
#>   name  score      rank_date
#>   <chr> <date>         <int>
#> 1 A     2021-03-21         3
#> 2 A     2021-04-21         2
#> 3 A     2021-05-21         1
#> 4 B     2021-06-21         1
#> 5 C     2021-07-21         1
#> 6 D     2021-03-21         1

Created on 2021-04-25 by the reprex package (v2.0.0)

3
votes

The assignment should be either at the top (<-). If we need to update the same object, do the assignment to the same object 'df'

library(dplyr)
df <- df %>% 
   group_by(name) %>%
   mutate(rank_date = order(score, decreasing = TRUE))  %>%
   ungroup

-output

df
# A tibble: 6 x 3
#  name  score      rank_date
#  <chr> <date>         <int>
#1 A     2021-03-21         3
#2 A     2021-04-21         2
#3 A     2021-05-21         1
#4 B     2021-06-21         1
#5 C     2021-07-21         1
#6 D     2021-03-21         1

or at the end (->) to an object

df %>% 
   group_by(name) %>%
   mutate(rank = order(score, decreasing = TRUE)) %>%
   ungroup -> df