Home > Net >  Apply function row by row on two adjacent rows
Apply function row by row on two adjacent rows

Time:10-04

I have a function that requires two subsequent rows as parameters, i.e.

calc <- function(x, y){
    return(x/1.07*y)
}

where x = data[i,1] and y = data[i-1,1]. The function should be applied row by row starting at row two. I cannot find a way to pass the y as an argument. Is there any way to do this without using a for-loop?

CodePudding user response:

It is difficult to know without a reproducible example, but here's a base R example:

x <- 1:10
c(NA, x[-1] / (1.07*x[-length(x)]))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422

You'll need a vector whose length is the same as the number of rows, so you need to append NA in the first value.

Or with dplyr::lag:

library(dplyr)
x / (1.07*lag(x))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422

Or with data.table::shift:

library(data.table)
x / (1.07*shift(x))
#[1]  NA 1.869159 1.401869 1.246106 1.168224 1.121495 1.090343 1.068091 1.051402 1.038422
  •  Tags:  
  • r
  • Related