AnswerBun.com

How to keep column attribute when converting object class to Date in R

I have an object mydf:

mydf <- structure(list(USUBJID = structure(c("ID1", "ID2", 
"ID3", "ID4", "ID5", 
"ID6"), label = "ID"), MYDATE = structure(c("2012-03-06", 
"2013-04-09", "2014-06-11", "2011-03-24", "2018-01-08", "2010-03-14"
), label = "Date")), row.names = c("1", "2", 
"3", "4", "5", 
"6"), class = "data.frame")

> mydf
  USUBJID     MYDATE
1     ID1 2012-03-06
2     ID2 2013-04-09
3     ID3 2014-06-11
4     ID4 2011-03-24
5     ID5 2018-01-08
6     ID6 2010-03-14

sapply(mydf, class)
    USUBJID      MYDATE 
"character" "character" 

attributes(mydf$MYDATE)$label
[1] "Date"

When I convert mydf$MYDATE to class Date as follows:

mydf <- mydf %>% mutate(
    MYDATE = as.Date(MYDATE)
)

sapply(mydf, class)
    USUBJID      MYDATE 
"character"      "Date"

attributes(mydf$MYDATE)$label
NULL

It looses the label attribute. How can I convert it to Date, but without removing the label attribute?

Stack Overflow Asked by icedcoffee on January 29, 2021

1 Answers

One Answer

You can use [] like:

mydf$MYDATE[] <- as.Date(mydf$MYDATE)
class(mydf$MYDATE) <- "Date"
attributes(mydf$MYDATE)$label
#[1] "Date"
class(mydf$MYDATE)
#[1] "Date"

Answered by GKi on January 29, 2021

Add your own answers!

Related Questions

How Can I Not Double Count Rows And Objects In My Query?

3  Asked on November 22, 2021 by ziegler199

       

Login with active directory

0  Asked on November 20, 2021 by artisan

       

External CSS not linking for all elements

1  Asked on November 20, 2021 by stratos-la

   

Why is ‘u{1D11E}’.charAt(0) not equal to ‘u{1D11E}’?

2  Asked on November 20, 2021 by json-prime

     

E: Unable to locate package python3-boto3

2  Asked on November 20, 2021 by rosi-darmawati

       

x and o in tic tac toe keeps alternating

0  Asked on November 20, 2021 by channee-mathmath

     

Remove using a button

2  Asked on November 20, 2021 by gastn

   

remove 0 and add ‘ ‘ in every number in pandas

1  Asked on November 20, 2021 by spt-hsb

   

nav-tabs doesn’t change on click

0  Asked on November 20, 2021 by beureu

     

Stick element on bottom on page scroll

3  Asked on November 20, 2021

         

Exchange each 100 in a dataframe for another value

1  Asked on November 20, 2021 by tarik-benrabah

     

GraphQL & Using a nested subscribe function

1  Asked on November 20, 2021 by u-rogel

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved.