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

Time:06-02

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)

CodePudding user response:

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.

CodePudding user response:

Using ISOdate.

do.call(ISOdate, unname(transform(df.data, years=years   2000)[c(3, 1, 2)])) |> as.Date()
# [1] "2016-01-22" "2017-02-01" "2018-03-23" "2018-10-29" "2015-12-14"
  • Related