data<-read.csv("d:/TEMP/Data.csv", header=TRUE)
str(data)
head(data)
ShiftDate
1 01-10-2024 0:00
2 01-10-2024 0:00
3 01-10-2024 0:00
4 01-10-2024 0:00
5 01-10-2024 0:00
6 01-10-2024 0:00
data %>%
mutate(ShiftDate = as.Date(ShiftDate, format = "%d/%m"))
#result should by :01-10 and so on
Try format()
function:
date <- c("01-10-2024 0:00", "02-10-2024 0:00", "03-11-2024 0:00")
as.Date(date, tryFormats = "%d-%m-%Y") |>
format("%d/%m")
#> [1] "01/10" "02/10" "03/11"
Created on 2024-10-28 with reprex v2.1.0
> library(readr)
> date <- read_csv("D:/TEMP/date.csv")
Rows: 6 Columns: 1
── Column specification ───────────────────────────────────────────────────────────────────────────────────────────────────────
Delimiter: ","
chr (1): ShiftDate
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
> date
# A tibble: 6 × 1
ShiftDate
<chr>
1 1-10-2024
2 1-11-2024
3 1-12-2024
4 1-13-2024
5 1-14-2024
6 1-15-2024
> str(date)
spc_tbl_ [6 × 1] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
$ ShiftDate: chr [1:6] "1-10-2024" "1-11-2024" "1-12-2024" "1-13-2024" ...
- attr(*, "spec")=
.. cols(
.. ShiftDate = col_character()
.. )
- attr(*, "problems")=<externalptr>
> head(date)
# A tibble: 6 × 1
ShiftDate
<chr>
1 1-10-2024
2 1-11-2024
3 1-12-2024
4 1-13-2024
5 1-14-2024
6 1-15-2024
> date<-date %>%
+ mutate(ShiftDate = as.Date(ShiftDate, format("%m-%d")))
> date
# A tibble: 6 × 1
ShiftDate
<date>
1 2024-01-10
2 2024-01-11
3 2024-01-12
4 2024-01-13
5 2024-01-14
6 2024-01-15
Dates in R are always always displayed as YYYY-MM-DD. The as.Date function returns dates and its format
argument tells the function the format of the incoming dates.
If you want a character column displaying the day/month as characters, you can use the format() function, as @gsapijaszko suggested. Here is some code showing the original characters changed into dates and into characters as day/month.
library(tidyverse)
DF <- tibble(ShiftDate = c('1-10-2024',
'1-11-2024',
'1-12-2024',
'1-13-2024',
'1-14-2024',
'1-15-2024'))
DF
#> # A tibble: 6 × 1
#> ShiftDate
#> <chr>
#> 1 1-10-2024
#> 2 1-11-2024
#> 3 1-12-2024
#> 4 1-13-2024
#> 5 1-14-2024
#> 6 1-15-2024
DF |> mutate(Date = as.Date(ShiftDate, format = "%m-%d-%Y"),
DayMon = format(as.Date(ShiftDate, format = "%m-%d-%Y"), "%d/%m"))
#> # A tibble: 6 × 3
#> ShiftDate Date DayMon
#> <chr> <date> <chr>
#> 1 1-10-2024 2024-01-10 10/01
#> 2 1-11-2024 2024-01-11 11/01
#> 3 1-12-2024 2024-01-12 12/01
#> 4 1-13-2024 2024-01-13 13/01
#> 5 1-14-2024 2024-01-14 14/01
#> 6 1-15-2024 2024-01-15 15/01
Created on 2024-10-28 with reprex v2.1.1