Home > Net >  In xtfrm.data.frame(x) : cannot xtfrm data frames warning when sorting data frame
In xtfrm.data.frame(x) : cannot xtfrm data frames warning when sorting data frame

Time:11-28

I have tried two methods to sort a data frame by column values:

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

and they both trigger the same warning message:

Warning messages:
1: In xtfrm.data.frame(x) : cannot xtfrm data frames
2: In xtfrm.data.frame(x) : cannot xtfrm data frames

How do I avoid this?

CodePudding user response:

Here are some alternatives. All use fmt defined in (1).

1) Base R The date format is ambiguous but choose one of the fmt values below. Then pick ou8t the desired column, convert it to Date class, find the indexes which would sort it and then apply them.

# 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) zoo Another possibility is to convert it to a zoo object and then possibly back. The conversion automatically sorts it and converts it to Date class. If a zoo object is ok as a result then omit the last line.

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 We can convert the dates and then use arrange to sort.

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
  • Related