是否可以将数据加载到具有不同日期时间格式的R中?例如,我有一个开始的.csv文件:
DATE,d1,d2
1990-12-07 09:36,6.1,3.7
1990-12-07 10:36,6.9,3.7
1990-12-07 11:36,6.9,3.7
1990-12-07 16:36,8.1,4
1990-12-07 18:36,7,3.9
1990-12-07 21:36,6.5,3.8
1990-12-07 22:36,6.4,3.8
07/13/1990 06:36,5.4,3.7
07/13/1990 13:36,5.3,4.2
07/13/1990 14:36,5.2,4.6
07/13/1990 15:36,5,4.2
07/13/1990 16:36,5.1,4.2
其中日期时间格式从这两种格式中随机变化。试图以标准方式将此文件加载到R中,返回:
d <- read.table('filename.csv',
header = TRUE, sep = ',')
> d[1:9,]
DATE T1 T2
1 1990-12-07 09:36 6.1 3.7
2 1990-12-07 10:36 6.9 3.7
3 1990-12-07 11:36 6.9 3.7
4 1990-12-07 16:36 8.1 4.0
5 1990-12-07 18:36 7.0 3.9
6 1990-12-07 21:36 6.5 3.8
7 1990-12-07 22:36 6.4 3.8
8 07/13/1990 06:36 5.4 3.7
9 07/13/1990 13:36 5.3 4.2
有没有办法从read.table中将这些格式化为标准格式?
举个例子:
这两种日期显示为:
yyyy-dd-mm HH:MM
和
mm/dd/yyyy HH:MM
不确定为什么他们决定使用这种randon格式。
我希望输出为:
DATE,d1,d2
1990-07-12 09:36,6.1,3.7
1990-07-12 10:36,6.9,3.7
1990-07-12 11:36,6.9,3.7
1990-07-12 16:36,8.1,4
1990-07-12 18:36,7,3.9
1990-07-12 21:36,6.5,3.8
1990-07-12 22:36,6.4,3.8
1990-07-13 06:36,5.4,3.7
1990-07-13 13:36,5.3,4.2
1990-07-13 14:36,5.2,4.6
1990-07-13 15:36,5,4.2
1990-07-13 16:36,5.1,4.2
答案 0 :(得分:3)
如果您要操作它们,最好确保您的值为character
类,因此在读取数据时添加, stringsAsFactors = FALSE
。然后,我们可以使用一些正则表达式来操纵只有感兴趣的值
添加, stringsAsFactors = FALSE
df <- read.csv(text = "DATE,d1,d2
1990-12-07 09:36,6.1,3.7
1990-12-07 10:36,6.9,3.7
1990-12-07 11:36,6.9,3.7
1990-12-07 16:36,8.1,4
1990-12-07 18:36,7,3.9
1990-12-07 21:36,6.5,3.8
1990-12-07 22:36,6.4,3.8
07/13/1990 06:36,5.4,3.7
07/13/1990 13:36,5.3,4.2
07/13/1990 14:36,5.2,4.6
07/13/1990 15:36,5,4.2
07/13/1990 16:36,5.1,4.2", stringsAsFactors = FALSE)
识别错误的格式并修复它
indx <- grepl("/", df$DATE)
df[indx, "DATE"] <- sub("(\\d{2})/(\\d{2})/(\\d{4})", "\\3-\\2-\\1", df[indx, "DATE"])
df
# DATE d1 d2
# 1 1990-12-07 09:36 6.1 3.7
# 2 1990-12-07 10:36 6.9 3.7
# 3 1990-12-07 11:36 6.9 3.7
# 4 1990-12-07 16:36 8.1 4.0
# 5 1990-12-07 18:36 7.0 3.9
# 6 1990-12-07 21:36 6.5 3.8
# 7 1990-12-07 22:36 6.4 3.8
# 8 1990-13-07 06:36 5.4 3.7
# 9 1990-13-07 13:36 5.3 4.2
# 10 1990-13-07 14:36 5.2 4.6
# 11 1990-13-07 15:36 5.0 4.2
# 12 1990-13-07 16:36 5.1 4.2