track type shortcut player system_played date time_period time record_duration
<chr> <chr> <chr> <chr> <chr> <date> <chr> <dbl> <dbl>
1 Luigi Racew~ Three ~ No Salam NTSC 1997-02-15 2M 12.99S 133. 1
2 Luigi Racew~ Three ~ No Dan PAL 2020-11-06 1M 57.77S 118. 112
3 Moo Moo Farm Three ~ No Gregg G NTSC 1997-03-07 1M 35.48S 95.5 81
4 Moo Moo Farm Three ~ No MR PAL 2020-02-18 1M 25.93S 85.9 374
5 Koopa Troop~ Three ~ No Launsp~ NTSC 1997-05-27 1M 42.01S 102. 95
6 Koopa Troop~ Three ~ No Dan PAL 2020-07-13 1M 35.29S 95.3 0
I have a dataset as above, and now I want to replace the column "date" with a new column "newdate" that contains the SAME values but under DIFFERENT names. For each "track", the earliest "date" will become "First", and the latest date will become "Last".
I tried this code:
mydata <- data %>%
group_by(track) %>%
mutate(newdate = recode(date, "First", .default = "Last"))
And encountered an error message:
Error: Problem with
mutate()
inputnewdate
. x no applicable method for 'recode' applied to an object of class "Date" i Inputnewdate
isrecode(date, "First", .default = "Last")
. i The error occurred in group 1: track = "Banshee Boardwalk".
Is there an alternative function for recode() that could apply for "Date" class values?
CodePudding user response:
If we want to change the min
and max
date to character
elements, we need to first convert the date
from Date
class to character
library(dplyr)
mydata <- data %>%
group_by(track) %>%
mutate(newdate = case_when(date == min(date) ~ "First",
date == max(date) ~ "Last", TRUE ~ as.character(date)))