conditional conversion from character to date for a dataframe column in r

时光总嘲笑我的痴心妄想 提交于 2021-01-28 11:20:44

问题


I have a dataframe I read from an excel file, like below. Date turned out to be in 5-digits format or a date string format.

df = data.frame(Date = c('42195', '3/31/2016', '42198'), Value = c(123, 445, 222))

Date     Value
42195      123          
3/31/2016  445          
42198      222  

I want to clean up the column and convert everything into date format. I did the following.

df %>% 
  mutate(Date = ifelse(length(Date)==5,as.Date(Date, origin = '1899-12-30'), as.Date(Date) ))

I got error like this:

Error in charToDate(x) : character string is not in a standard unambiguous format

What did I do wrong? I could not figure out why after many attempts to fix it. Thanks a lot.


回答1:


There are few changes that you need to do :

1) Instead of length(Date)==5, I guess you are looking for nchar

2) To change excel date to R date, they need to be numeric. Currently they are factors.

3) You need to provide specific format to as.Date when date is not in standard format.

4) Use if_else instead of ifelse since the latter would change them to numbers.

library(dplyr)

df %>% 
  mutate(Date = as.character(Date),
         Date = if_else(nchar(Date) ==5, 
                   as.Date(as.numeric(Date), origin = '1899-12-30'), 
                   as.Date(Date, "%m/%d/%Y")))

#        Date Value
#1 2015-07-10   123
#2 2016-03-31   445
#3 2015-07-13   222


来源:https://stackoverflow.com/questions/60254796/conditional-conversion-from-character-to-date-for-a-dataframe-column-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!