Home > Software engineering >  convert column of date to char in R, keeping same format
convert column of date to char in R, keeping same format

Time:02-24

I have:

library(tidyverse)
library(lubridate)
data <- tibble(date = ymd("20220224"),
       number = 1234,
       decimal = 12.34,
       char = "20220224")
)

I want to convert the date column to character, and keep the exact format, ie 2022-02-24

performing as.character(ymd("20220224")) works perfectly, and I get "2022-02-24"

but, when I apply this to the column, data[,"date"] = as.character(data[,"date"]), I get the char of the date counting days since Jan 1, 1970.

enter image description here

How can I get it so that I get the characters as desired? I want to see "2022-02-24", not "19047"

thanks

CodePudding user response:

tibble will return a tibble after you have subsetted it using [. Therefore you need to use [[.

library(tidyverse)
library(lubridate)

data[,"date"] = as.character(data[["date"]])

# A tibble: 1 x 4
  date       number decimal char    
  <chr>       <dbl>   <dbl> <chr>   
1 2022-02-24   1234    12.3 20220224

CodePudding user response:

This is quite easy with the command as.character()


library(tidyverse)
library(lubridate)
data <- tibble(date = ymd("20220224"),
               number = 1234,
               decimal = 12.34,
               char = "20220224")
)

data$date <- as.character(data$date)

View(data)

data

enter image description here

CodePudding user response:

Just wrap it around as.character()

library(dplyr)

data %>% 
  mutate(date = as.character(date))

  date       number decimal char    
  <chr>       <dbl>   <dbl> <chr>   
1 2022-02-24   1234    12.3 20220224

OR as a new column:

data %>% 
  mutate(char_new = as.character(date))

  date       number decimal char     char_new  
  <date>      <dbl>   <dbl> <chr>    <chr>     
1 2022-02-24   1234    12.3 20220224 2022-02-24

data:

structure(list(date = structure(19047, class = "Date"), number = 1234, 
    decimal = 12.34, char = "20220224"), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -1L))

CodePudding user response:

If you'd like to do it within tidyverse you can do it within a mutate function.

data <- tibble(date = ymd("20220224"),
               number = 1234,
               decimal = 12.34,
               char = "20220224") %>% 
               mutate(date = as.character(date))

This will return

  date       number decimal char    
  <chr>       <dbl>   <dbl> <chr>   
1 2022-02-24   1234    12.3 20220224
  •  Tags:  
  • r
  • Related