我尝试了两种方法来按列值对数据帧进行排序:
dateCol = "DATE"
df <- data.frame( DATE = c("01-10-2020","01-04-2020","01-06-2020","01-02-2020"),
VAL = c(3,7,4,5))
# Method 1
df <- df[order(df[dateCol]),]
# Method 2
df <- df[order(df[which(colnames(df)==dateCol)]),]
它们都触发了同样的警告信息:
Warning messages:
1: In xtfrm.data.frame(x) : cannot xtfrm data frames
2: In xtfrm.data.frame(x) : cannot xtfrm data frames
我怎么才能避免这种情况?
发布于 2022-11-27 22:40:01
以下是一些替代方案。所有这些都使用(1)中定义的fmt
。
1) Base 日期格式不明确,但请选择下面的fmt
值之一。然后选择ou8t所需的列,将其转换为Date类,找到将其排序的索引,然后应用它们。
# choose one of the following
fmt <- "%d-%m-%Y"
fmt <- "%m-%d-%Y"
df2 <- df # in case we need to preserve input
df2[[dateCol]] <- as.Date(df2[[dateCol]], fmt)
o <- order(df2[[dateCol]])
df2[o, ]
## DATE VAL
## 4 2020-01-02 5
## 2 2020-01-04 7
## 3 2020-01-06 4
## 1 2020-01-10 3
2) 动物园的另一种可能是把它转换成动物园的物体,然后可能返回。转换会自动对其排序并将其转换为Date类。因此,如果动物园对象是可以的,那么就省略最后一行。
library(zoo)
VAL <- read.zoo(df, index = dateCol, format = fmt)
fortify.zoo(VAL, name = dateCol)
## DATE VAL
## 1 2020-01-02 5
## 2 2020-01-04 7
## 3 2020-01-06 4
## 4 2020-01-10 3
3) dplyr我们可以转换日期,然后使用进行排序。
library(dplyr)
df %>%
mutate(!!dateCol:=as.Date(.[[dateCol]], fmt)) %>%
arrange(.[[dateCol]])
## DATE VAL
## 1 2020-01-02 5
## 2 2020-01-04 7
## 3 2020-01-06 4
## 4 2020-01-10 3
https://stackoverflow.com/questions/74594259
复制相似问题