首页 > 解决方案 > 使用逻辑更改 R 中的日期格式

问题描述

这里的新 R 用户 - 我有许多 .csv 文件,其中一列包含时间戳(date_time),另一列包含温度读数。我正在尝试编写一个检测 date_time 格式的函数,然后将其更改为不同的格式。由于收集数据的方式,某些 .csv 文件中的日期/时间格式不同。我希望该函数将所有文件的 date_time 更改为相同的格式。

我想要的日期时间格式:%m/%d/%y %H:%M:%S 我想要更改为上述日期时间格式:“%y-%m-%d %H:%M:%S”

> head(file1data)
  x         date_time temperature coupler_d coupler_a host_con stopped EoF
1 1 18-07-10 09:00:00      41.137    Logged                               
2 2 18-07-10 09:15:00      41.322                                         
3 3 18-07-10 09:30:00      41.554                                         
4 4 18-07-10 09:45:00      41.832                                         
5 5 18-07-10 10:00:00      42.156                                         
6 6 18-07-10 10:15:00      42.755                                         
> head(file2data)
  x            date_time temperature coupler_d coupler_a host_con stopped EoF
1 1 07/10/18 01:00:00 PM       8.070    Logged                               
2 2 07/10/18 01:15:00 PM       8.095                                         
3 3 07/10/18 01:30:00 PM       8.120                                         
4 4 07/10/18 01:45:00 PM       8.120                                         
5 5 07/10/18 02:00:00 PM       8.020                                         
6 6 07/10/18 02:15:00 PM       7.795 

file2data 格式正确。file1data 不正确。

我尝试使用逻辑来检测和替换日期格式,例如,

file1data %>% 
if(str_match_all(date_time,"([0-9][0-9]{2})[-.])")){
  format(as.POSIXct(date_time,format="%y-%m-%d %H:%M:%S"),"%m/%d/%y %H:%M:%S")
}else{format(date_time,"%m/%d/%y %H:%M:%S")}

但这不起作用,我收到以下错误:

Error in if (.) str_match_all(date_time, "([0-9][0-9]{2})[-.])") else { : 
  argument is not interpretable as logical
In addition: Warning message:
In if (.) str_match_all(date_time, "([0-9][0-9]{2})[-.])") else { :
  the condition has length > 1 and only the first element will be used

有任何想法吗?

标签: r

解决方案


推荐阅读