R函数,我的as.date有错误吗?我得到一个错误不知道如何将 df 转换为 class

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

嗨,谁能帮我解决这个问题,我遇到了这个错误。 as.Date.default(x = df, format = "%m %d, %y") 中的错误: 不知道如何将 'df' 转换为 class “日期”

欣赏。

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)

我不确定你到底想要什么,但你没有把 monthsdaysyears 放在一起。

例如,

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

此代码将生成日期 date

如果你想要功能,

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)

会起作用。

使用 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"