r中数据框列从字符到日期的条件转换 [英] conditional conversion from character to date for a dataframe column in r

查看:68
本文介绍了r中数据框列从字符到日期的条件转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从excel文件读取的数据框,如下所示. Date 的格式为5位数字或日期字符串格式.

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) ))

我遇到这样的错误:

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)我猜您正在寻找的是 nchar

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

2)要将excel日期更改为R date,它们必须为数字.当前它们是因素.

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

3)如果日期不是标准格式,则需要为 as.Date 提供特定格式.

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

4)使用 if_else 代替 ifelse ,因为后者会将它们更改为数字.

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

这篇关于r中数据框列从字符到日期的条件转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆