无法在R中使用强制转换命令对数字列名称进行排序

时间:2019-03-30 11:52:34

标签: r

我有列名,例如0:00:00 1:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00。

如您所见,时间戳1:00:00之后是10:00:00,而不是02:00:00。

通过深入探讨此问题,解决了在数据框中对值进行排序并将值的数据类型转换为数字的问题。

我们如何将列名转换为数字并排序列而不是数据?

1 个答案:

答案 0 :(得分:0)

我制作了一个样本数据集来说明我的解决方案:使用lubridate,我们可以将colnames转换为时间格式,然后相应地对data.frame进行排序:

df <- structure(list(`0:00:00` = 1:9, `1:00:00` = 10:18, `10:00:00` = 19:27, 
    `11:00:00` = 28:36, `12:00:00` = 37:45, `13:00:00` = 46:54, 
    `14:00:00` = 55:63), .Names = c("0:00:00", "1:00:00", "10:00:00", 
"11:00:00", "12:00:00", "13:00:00", "14:00:00"), class = "data.frame", row.names = c(NA, 
-9L))

df2 <- structure(list(`0:00:00` = 1:9, `1:00:00` = 19:27, `10:00:00` = 28:36, 
    `11:00:00` = 10:18, `12:00:00` = 37:45, `13:00:00` = 46:54, 
    `14:00:00` = 55:63), .Names = c("0:00:00", "1:00:00", "10:00:00", 
"11:00:00", "12:00:00", "13:00:00", "14:00:00"), class = "data.frame", row.names = c(NA, 
-9L))

library(lubridate)
df <- df[,order(hms(names(df)))]
df2 <- df2[,order(hms(names(df2)))]