Function using as successive values of a column (R)

6

I have a data.frame with 13 columns and 78 rows. I need to do for each column ((x1/x2)^12)-1 , being x1 the value contained in the first row of the first column, x2 the value contained in the second row of the first column, and I need to apply this function for all rows. To automate the process I thought of using the rollapply function, the problem is in the elaboration of the function. How can I, in r, use the successive values of a column as arguments to a function?

    
asked by anonymous 04.06.2014 / 22:12

2 answers

4

You can use sapply along with mapply . Doing with an example data.frame :

set.seed(1)
dados <- data.frame(x=rnorm(100), y=rnorm(100))
resultados <- sapply(dados, function(col) mapply(function(x1, x2) ((x1/x2)^12)-1, 
                                  x1=col[1:(length(col)-1)], 
                                  x2=col[2:(length(col))]))

By explaining the code a bit better, mapply will apply the function(x1, x2) ((x1/x2)^12)-1 function using as x1 elements from 1 to n-1 and as x2 elements from 2 to n. And sapply will cause this function to scroll through all the columns of your data.frame . The result will therefore be matrix with the same number of columns as the original data.frame but with one less observation:

head(resultados)
                 x             y
[1,]  2.482943e+06  1.043354e+14
[2,] -1.000000e+00 -1.000000e+00
[3,] -9.995733e-01  1.345669e+09
[4,]  1.658279e+08 -1.000000e+00
[5,] -9.999824e-01 -9.999933e-01
[6,]  5.163748e+02  5.053287e+04
    
05.06.2014 / 20:26
1

The solution using rollapply would be:

require(zoo)
set.seed(1)
dados <- data.frame(x=rnorm(100), y=rnorm(100))
rollapply(dados, FUN = function(x) (x[1]/x[2])^12 - 1, width = 2, align = 'r')
    
09.06.2014 / 01:02