Function using as arguments successive values of a column (R)

Asked

Viewed 446 times

6

I have a data.frame with 13 columns and 78 rows. I need to do it for each column ((x1/x2)^12)-1, being x1 the value 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 to all lines. To automate the process I thought to use the function rollapply, the problem is in the function design. How can I, in r, use the successive values of a column as arguments of a function?

  • "where X1 is the value contained in the first row of the first column, x2 is the value contained in the second row of the first column, and this function must be applied for all rows". Here you mean you need to apply the function to all columns, right?

2 answers

4


You can use the sapply along with the mapply. Making with a data.frame for example:

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))]))

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

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
  • 1

    Carlos, thank you very much. That’s right.

1

The solution using the rollapplywould 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')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.