Skip to content

fill data forward in data frame.

3 messages · Ben quant, Petr Savicky

#
On Thu, Mar 01, 2012 at 02:31:01PM -0700, Ben quant wrote:
Hi.

Try first the following simpler version.

  # an input vector
  x <- rep(NA, times=20)
  x[4] <- "A"
  x[9] <- "B"
  x[17] <- "C"

  # extending the values forward 
  values <- c(NA, x[!is.na(x)])
  ind <- cumsum(!is.na(x)) + 1
  y <- values[ind]

  # compare with the original
  cbind(x, y)

        x   y  
   [1,] NA  NA 
   [2,] NA  NA 
   [3,] NA  NA 
   [4,] "A" "A"
   [5,] NA  "A"
   [6,] NA  "A"
   [7,] NA  "A"
   [8,] NA  "A"
   [9,] "B" "B"
  [10,] NA  "B"
  [11,] NA  "B"
  [12,] NA  "B"
  [13,] NA  "B"
  [14,] NA  "B"
  [15,] NA  "B"
  [16,] NA  "B"
  [17,] "C" "C"
  [18,] NA  "C"
  [19,] NA  "C"
  [20,] NA  "C"

This could be applied directly to the last two columns of your
data frame "xx". However, it may be more natural to obtain the
vector "values" from the input data and not from their sparse
form, which is the data frame. Also, the logical vector !is.na(x)
is the same for the last two columns of your data frame, so
it may be computed only once.

Hope this helps.

Petr Savicky.