[R] Processing key_column, begin_date, end_date in R

JS Huang js.huang at protective.com
Thu Feb 26 06:15:05 CET 2015


Hi,

  It's not as easy as I originally thought.  Here is a revision with the
function beginEnd to get it done.

> date
  key_column begin_date    end_date
1     123456 2013-01-01 2014-01-01 
2     123456 2013-07-01 2014-07-01 
3     789102 2012-03-01 2014-03-01 
4     789102 2015-02-01 2016-02-01 
5     789102 2015-02-06  2016-02-06
> beginEnd
function()
{
  date[order(date$key_column,date$begin_date),]
  key <- numeric(0)
  begin <- character(0)
  end <- character(0)
  currentKey <- as.numeric(date$key_column[1])
  key <- c(key, currentKey)
  currentBegin <- as.character(date$begin_date[1])
  begin <- c(begin, currentBegin)
  currentEnd <- as.character(date$end_date[1])
  for (i in 2:length(date$key_column))
  {
    if (currentKey == as.numeric(date$key_column[i]))
    {
      if (currentEnd >= as.character(date$begin_date[i]))
      {
        currentEnd <- max(currentEnd, as.character(date$end_date[i]))
      }
      else
      {
        end <- c(end, currentEnd)
        currentKey <- as.numeric(date$key_column[i])
        key <- c(key, currentKey)
        currentBegin <- as.character(date$begin_date[i])
        begin <- c(begin, currentBegin)
        currentEnd <- as.character(date$end_date[i])        
      }
      if (i == length(date$key_column))
      {
        end <- c(end, currentEnd)
      }
    }
    else
    {
      end <- c(end, currentEnd)
      currentKey <- as.numeric(date$key_column[i])
      key <- c(key, currentKey)
      currentBegin <- as.character(date$begin_date[i])
      begin <- c(begin, currentBegin)
      currentEnd <- as.character(date$end_date[i])
      if (i == length(date$key_column))
      {
        end <- list(end, currentEnd)
      }
    }
  }
  result <- cbind(key, begin, end)
  colnames(result) <- c("key.column","begin.date","end.date")
  return(result)
}
> beginEnd()
     key.column begin.date   end.date     
[1,] "123456"   "2013-01-01" "2014-07-01 "
[2,] "789102"   "2012-03-01" "2014-03-01 "
[3,] "789102"   "2015-02-01" "2016-02-06" 




--
View this message in context: http://r.789695.n4.nabble.com/Processing-key-column-begin-date-end-date-in-R-tp4703835p4703852.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list