0

I'm trying to implement an ordering algorithm based on dates of events in a data frame. The dates are strings of the form 07/10/1989 07:59 and I went through a process of extracting their numeric values and eventually got an array with 5 columns with rows of the form 7 10 89 7 59.

Here's the problem: I'm trying to sort the original data frame using this array of numeric values with for loops and if statements:

 for (i in 1:(L-1)){
  for (j in (i+1):L){
    if (Dates_Num[i,3] > Dates_Num[j,3]) {
      a    <- V[i]
      V[i] <- V[j]
      V[j] <- a
    }
    else if(match(Dates_Num[i,3], Dates_Num[j,3], nomatch = F) == 1) {
      if (Dates_Num[i,1] > Dates_Num[j,1]) {
        a    <- V[i]
        V[i] <- V[j]
        V[j] <- a ...

and there are more nestings of exactly the same form. The algorithm executes, and there's no loss of information, but it doesn't order the data frame by dates. For reference Dates_Num is my 5-column array of numeric dates, and initially V = 1:L where L is the number of rows in the data frame. I've tried on simple toy examples that if I give V the right permutation then Dates_Num[V,] should hopefully have the correct permutation, and same with the data frame. What am I doing wrong? Is there some kind of syntax I got wrong?

josliber
  • 43,891
  • 12
  • 98
  • 133
Mnifldz
  • 145
  • 12
  • 1
    Why you want to do this? R has the `order` and `sort` function to do this task. – nicola Jun 03 '15 at 19:31
  • 4
    This seems like a very odd way to do things. Why not just convert the date time values to proper Date/POSIXct values in R and use the standard sorting functions? It would help to give some sample input and desired output to make a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Jun 03 '15 at 19:33
  • @nicola Does it work on strings or do I need to convert the dates into integers? – Mnifldz Jun 03 '15 at 19:33
  • 5
    If `dates` is your vector with the dates, just try `sort(as.POSIXct(dates,format="%m/%d/%Y %H:%M"))` (assuming that the first digits are the months). – nicola Jun 03 '15 at 19:36

0 Answers0