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

R function, Is there an error with my as.date? I got an error do not know how to convert df to class

Hi can someone help me solve this, got this error. Error in as.Date.default(x = df, format = "%m %d, %y") :
do not know how to convert ‘df’ to class “Date”

Appreciate it.

df.data= data.frame(months = c(1,2,3,10,12),
                days = c(22,1,23,29,14),
                years = c(16,17,18,18,15)
)

col_date = function(df){
  df[,'date'] = as.Date(x = df.data, format = '%m %d, %y')
    return(df)
}

col_date(df = df.data)

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

>Solution :

I’m not sure what you exactly want but you didn’t put months, days, and years together.

For example,

library(dplyr)
df.data %>%
  rowwise %>%
  mutate(date = paste0(c(months, days, years), collapse = "-") %>%
           as.Date(., format = '%m-%d-%y')) 

  months  days years date         
   <dbl> <dbl> <dbl> <date>    
1      1    22    16 2016-01-22
2      2     1    17 2017-02-01
3      3    23    18 2018-03-23
4     10    29    18 2018-10-29
5     12    14    15 2015-12-14

this code will make date date.

If you want function,

col_date <- function(df){
  df <- df %>%
    rowwise %>%
    mutate(date = paste0(c(months, days, years), collapse = "-") %>%
             as.Date(., format = '%m-%d-%y')) 
  return(df)
}
col_date(df.data)

will works.

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