Search code examples
rdataframeapplylapplysapply

Apply operation on the next element of the data frame column vector


Let's say I have a df like this

df1 <- data.frame(ID = c(1, 2, 3, 4, 5, 6, 7, 8, 9),
                 var2 = c(2, 8, 0, 7, 3, 4, 1, 10, 13))

I want to get a vector of values which produce following operation:

(x-median(x-1))/median(x-1)

where this -1 refers to index of the element in column. For example, for first element in column var2 the result is:

(2-(median(c( 8, 0, 7, 3, 4, 1, 10, 13))) )/(median(c( 8, 0, 7, 3, 4, 1, 10, 13))) 
-0.63636

Thanks!


Solution

  • Using sapply, we can loop over index of each value in var2, ignore that value and calculate median of remaining values and perform the calculation.

    sapply(seq_along(df1$var2), function(i) {
        med_i <- median(df1$var2[-i])
       (df1$var2[i] - med_i)/med_i
    })
    #[1] -0.6364  1.2857 -1.0000  1.0000 -0.4545 -0.2000 -0.8182  1.8571  2.7143