简体   繁体   中英

Why I cannot save mutate result in r?

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))

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM