简体   繁体   中英

Apply function row by row on two adjacent rows

I have a function that requires two subsequent rows as parameters, ie

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM