Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert column of date to char in R, keeping same format

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading